Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading