Splitting a string into separate variables

StringPowershell

String Problem Overview


I have a string, which I have split using the code $CreateDT.Split(" "). I now want to manipulate two separate strings in different ways. How can I separate these into two variables?

String Solutions


Solution 1 - String

Like this?

$string = 'FirstPart SecondPart'
$a,$b = $string.split(' ')
$a
$b

Solution 2 - String

An array is created with the -split operator. Like so,

$myString="Four score and seven years ago"
$arr = $myString -split ' '
$arr # Print output
Four
score
and
seven
years
ago

When you need a certain item, use array index to reach it. Mind that index starts from zero. Like so,

$arr[2] # 3rd element
and
$arr[4] # 5th element
years

Solution 3 - String

It is important to note the following difference between the two techniques:

$Str="This is the<BR />source string<BR />ALL RIGHT"
$Str.Split("<BR />")
This
is
the
(multiple blank lines)
source
string
(multiple blank lines)
ALL
IGHT
$Str -Split("<BR />")
This is the
source string
ALL RIGHT 

From this you can see that the string.split() method:

  • performs a case sensitive split (note that "ALL RIGHT" his split on the "R" but "broken" is not split on the "r")
  • treats the string as a list of possible characters to split on

While the -split operator:

  • performs a case-insensitive comparison
  • only splits on the whole string

Solution 4 - String

Try this:

$Object = 'FirstPart SecondPart' | ConvertFrom-String -PropertyNames Val1, Val2
$Object.Val1
$Object.Val2

Solution 5 - String

Foreach-object operation statement:

$a,$b = 'hi.there' | foreach split .
$a,$b

hi
there

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondavetheraveView Question on Stackoverflow
Solution 1 - StringmjolinorView Answer on Stackoverflow
Solution 2 - StringvonPryzView Answer on Stackoverflow
Solution 3 - String0xGView Answer on Stackoverflow
Solution 4 - StringEsperento57View Answer on Stackoverflow
Solution 5 - Stringjs2010View Answer on Stackoverflow