Home > Net >  Split a string based on "|" character in PowerShell
Split a string based on "|" character in PowerShell

Time:10-07

I have a string variable in PowerShell which contains the value:

NFP|8dc3b47a-48eb-4696-abe2-48729beb63c8

I am attempting to get the beginning portion of that string into it's own variable by identifying the index of the "|" character and using a substring function to extract the first portion of the string, in this case "NFP". I am not sure how to escape the "|" so I can use it properly. It doesn't seem to recognize it at all. My latest attempt is as follows:

    $PolicyManual = $Item["PolicyManual"] 
    write-host $PolicyManual   #Displays NFP|8dc3b47a-48eb-4696-abe2-48729beb63c8

    if ($PolicyManual.Contains([regex]::escape("|"))) {
        $PolcyManual = $PolicyManual.Substring(0, $PolicyManual.IndexOf([regex]::escape("|")))
    }   

I'm sure this is simple, but I can't figure out how to make it work. Can anyone offer assistance to a PowerShell novice?

Thanks.

CodePudding user response:

The problem is that .contains method doesn't know about regex and you are never entering the if condition because of this. When you do [regex]::escape("|"), the method is looking for a literal \|.

Try this instead:

$PolicyManual = "NFP|8dc3b47a-48eb-4696-abe2-48729beb63c8"

if ($PolicyManual.Contains('|')) {
    $element0, $element1 = $PolicyManual.Split('|')
    $element0 #=> NFP
    $element1 #=> 8dc3b47a-48eb-4696-abe2-48729beb63c8
}
  • Related