I have a line a text and I want the first word to be a variable, the second to be a second but all the rest to be consider one single var.
For example splitting Mary had a little lamb would result in:
$var[1] = Mary$var[2] = had$var[4] = a little lambHow can I achieve this when I split by space?
If you know the exact length of the first two words you can use .substring. Otherwise, you can use -Split and then use -join after assigning the first two array entries to your variables.
$mySplit = "alpha bravo charlie delta" -split " "
$var1 = $mySplit[0]
$var2 = $mySplit[1]
$var3 = $mySplit[2..($mySplit.length+2)] -join " "
The above example for $var3 grabs the array created by the -split and gets every entry except the first 2. The -join will then join the array entries back together into a single string separating each entry by a space.
$a="Mary had a little lamb"
$v1,$v2,$v3=$a.split(" ",3)
The split is what turns a string into an array, the "3" is the limit of how many parts to split into, and the variable list to the left of "=" is what make the result to end up in corresponding variables.
PS > $v3
a little lamb 
PS >
                        Simply tell Split the number of elements to return:
$string = "Mary had a little lamb"
$var = $string.Split(" ",3)
Which will return:
Mary had a little lamb
You can then reference each element individually:
$var[0]
$var[1]
$var[2]
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With