Search code examples
powershellsplitsubstringdelimiter

split string in powershell using delimiter


i have the below powershell script:

$hostNames = "10.130.68.77, 172.29.207.33, ###, gcsl-blg7v=10.130.68.77, ndtv23v0675=172.29.207.33"
$iplist = $hostNames.Split(', ###, ')[0]
$dnsiplist = $hostNames.Split(', ###, ')[1]

Write-Host "COMPLETE LIST: $hostNames"
Write-Host "IP LIST: $iplist"
Write-Host "DNS-IP LIST: $dnsiplist"

Output:

COMPLETE LIST: 10.130.68.77, 172.29.207.33, ###, gcsl-blg7v=10.130.68.77, ndtv23v0675=172.29.207.33
IP LIST: 10.130.68.77
DNS-IP LIST: 

i wish to split on ', ###, ' so that i could get the below desired output:

COMPLETE LIST: 10.130.68.77, 172.29.207.33, ###, gcsl-blg7v=10.130.68.77, ndtv23v0675=172.29.207.33
IP LIST: 10.130.68.77, 172.29.207.33
DNS-IP LIST: gcsl-blg7v=10.130.68.77, ndtv23v0675=172.29.207.33

Please let me know how can i?


Solution

  • .Split uses the public string[] Split(params char[] separator); overload by default, in your example this means that the ', ###, ' is first converted to a char array [char[]] ', ###, ' and then split by each char. You need to help PowerShell to use the correct overload, public string[] Split(string[] separator, StringSplitOptions options);:

    $hostNames = '10.130.68.77, 172.29.207.33, ###, gcsl-blg7v=10.130.68.77, ndtv23v0675=172.29.207.33'
    $iplist, $dnsiplist = $hostNames.Split([string[]] ', ###, ', [System.StringSplitOptions]::None)
    
    Write-Host "COMPLETE LIST: $hostNames"
    Write-Host "IP LIST: $iplist"
    Write-Host "DNS-IP LIST: $dnsiplist"
    

    Note that this issue only happens in Windows PowerShell (.NET Framework), in PowerShell 7+ $hostNames.Split(', ###, ') would work just fine.

    It would be easier to use the regex-based -split operator in this case:

    $hostNames = '10.130.68.77, 172.29.207.33, ###, gcsl-blg7v=10.130.68.77, ndtv23v0675=172.29.207.33'
    $iplist, $dnsiplist = $hostNames -split ', ###, '
    
    Write-Host "COMPLETE LIST: $hostNames"
    Write-Host "IP LIST: $iplist"
    Write-Host "DNS-IP LIST: $dnsiplist"