SKID
SKID

Reputation: 33

Splitting a string character by character in Powershell

What I want to do: I have a string i.e "peter" and want to output the 1st character (p) in a variable. Then the first 2 charachters (pe) etc. until the end of the string (peter). At the end I would have 5 different variables. Could anyone help me out how to do that in powershell ?

What I have tried is:

$Inputstring ="peter"
$CharArray =$InputString.ToCharArray()
$CharArray

but this gave me

p
e
t
e
r

This here looks good:

$TstString = "peter"

$CharArray = $TstString.ToCharArray()
$CharArray[0]
$CharArray[0] + $CharArray[1]
$CharArray[0] + $CharArray[1]+ $CharArray[2]
$CharArray[0] + $CharArray[1]+ $CharArray[2]+ $CharArray[3]
$CharArray[0] + $CharArray[1]+ $CharArray[2]+ $CharArray[3] + $CharArray[4]

p
pe
pet
pete
peter

I want to use that for checking ActiveDirectory for existing email address and if exist like [email protected]; [email protected] ....

Upvotes: 3

Views: 2288

Answers (3)

Theo
Theo

Reputation: 61028

Here's an alternative approach for you

$str = 'peter'
$result = for ($len = 1; $len -le $str.Length; $len++) { $str.Substring(0, $len) }

Upvotes: 2

Lee_Dailey
Lee_Dailey

Reputation: 7479

here is another way to get it done. [grin] what it does ...

  • defines the string to work with
  • loops thru the number of chars in the string
  • uses the way that PoSh can index into a string by treating it as an array of chars to build a string
  • joins the chars into one string
  • sends that to a collection
  • shows the content of that on screen

you can address each variant with $Result[$Index], so there is no need for a hard-to-manage horde of variables. [grin]

the code ...

$InString = 'peter'

$Result = foreach ($Index in 0..($InString.Length - 1))
    {
    -join $InString[0..$Index]
    }

$Result

output ...

p
pe
pet
pete
peter

Upvotes: 2

mklement0
mklement0

Reputation: 437197

Here's a quick way to produce all prefix strings for a given string:

PS> $prefix = ''; ([char[]] 'peter').ForEach({ ($prefix += $_) })
p
pe
pet
pete
peter

$prefixes = ([char[] ... would capture all prefixes as a string array for later processing; alternatively, you can perform the processing directly inside the .ForEach() block (remove the (...) around the += assignment then, whose purpose is to also output the result of the assignment).

Upvotes: 2

Related Questions