Reputation: 33
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
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
Reputation: 7479
here is another way to get it done. [grin] what it does ...
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
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