PowerShell Split String into Variables

I have a line of text, and I want the first word to be a variable, the second to be the second, and everything else to be the only single var.

For example, splitting Mary had a little lambwill result in:

  • $var[1] = Mary
  • $var[2] = had
  • $var[4] = a little lamb

How can I achieve this when I share space?

+4
source share
3 answers

If you know the exact length of the first two words, you can use .substring. Otherwise, you can use -Splitand then use it -joinafter assigning the first two entries of the array to your variables.

$mySplit = "alpha bravo charlie delta" -split " "
$var1 = $mySplit[0]
$var2 = $mySplit[1]
$var3 = $mySplit[2..($mySplit.length+2)] -join " "

$var3 , -Split, , . -join , .

+3
$a="Mary had a little lamb"
$v1,$v2,$v3=$a.split(" ",3)

split - , , "3" - , "=" - .

PS > $v3
a little lamb 
PS >
+4

Just tell the Splitnumber of items returned:

$string = "Mary had a little lamb"
$var = $string.Split(" ",3)

What will return:

Mary
had
a little lamb

Then you can reference each element separately:

$var[0]
$var[1]
$var[2]
+1
source

Source: https://habr.com/ru/post/1681284/


All Articles