Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string character by character in Powershell

Tags:

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] ....

like image 285
SKID Avatar asked Nov 26 '25 10:11

SKID


1 Answers

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).

like image 174
mklement0 Avatar answered Nov 29 '25 01:11

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!