Search code examples
powershell

does not work split on powershell


I have code, which split string to array. So can you help me, why this is doesn't work?

$var="test.1->test.2"
$arr=$var.Split("->")
$arr[0]#show correct: "test.1"
$arr[1]#doesn't show...

Solution

  • It works. But it did split the string by "-" OR ">", so $arr[1] has empty string between "-" and ">", and "test.2" is in $arr[2].

    So you can either:

    $var="test.1->test.2"
    $arr=$var.Split("->")
    write-host $arr[0]
    write-host $arr[2]
    

    or:

    $var="test.1->test.2"
    $arr=$var.Split("->") | select -First 1 -Last 1
    write-host $arr[0]
    write-host $arr[1]
    

    or something like:

    $var="test.1->test.2"
    $arr= $($var -replace "->","#").Split("#") 
    write-host $arr[0]
    write-host $arr[1]