EN VI

split string in powershell using delimiter?

2024-03-13 08:30:04
How to 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"
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login