Reputation: 18197
I am having an array $IPAddress which contains IPv4 and IPv6 address like below.
IPAddress : {166.33.77.15, fe90::68fe:7602:d981:2cb}
IPAddress : {166.33.77.18, fe87::67c0:8476:3509:fb7a}
IPAddress : {166.33.77.65, fe80::c08e:f5ec:5095:e7ec}
I would like to store in my IPaddress array only the IPv4 address. I need to cut after '{' till ','. How to do this using powershell?
Upvotes: 0
Views: 270
Reputation: 68311
I got pretty much the same answer as Shay, but I'll add that you don't need to foreach the replace. It'll do the entire array at once:
$array -replace '^IPAddress : {([^,]+).+$','$1'
Upvotes: 0
Reputation: 60938
This is a way but I think (not... I'm sure!) there's something better using regex!
$IPAddress = $IPAddress | % { $_.Substring( $_.IndexOf('{')+1 , $_.IndexOf(',') - ($_.IndexOf('{')+1))
Edit: simple way with regex (not verifying if IP address is a valid ipaddress)
$IPAddress = $IPAddress | select-string "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" | select -ExpandProperty matches | select -ExpandProperty value
Upvotes: 0
Reputation: 37202
You can use regular expressions in PowerShell very easily for this.
$IPAddress = @(`
"IPAddress : {166.33.77.15, fe90::68fe:7602:d981:2cb}", `
"IPAddress : {166.33.77.18, fe87::67c0:8476:3509:fb7a}", `
"IPAddress : {166.33.77.65, fe80::c08e:f5ec:5095:e7ec}")
foreach($ip in $IPAddress) {
if ($ip -match "{.*,") {
Write-Host $matches[0].substring(1, $matches[0].length - 2)
}
}
$matches
is a special variable which is set after using the -match
operator.
Upvotes: 0
Reputation: 126862
If the result is an object then you can simply do:
$IPAddress[0]
If it's a string, try using a regex:
'IPAddress : {166.33.77.15, fe90::68fe:7602:d981:2cb}' -replace '^IPAddress : {([^,]+).+$','$1'
Upvotes: 2