2

Im extracting a list of IPs from a JSON file using the following syntax

$Request = 'https://url-to-json.com/file.json'
$AWSIPs = Invoke-WebRequest $Request | ConvertFrom-Json | Select-Object prefix -ExpandProperty prefixes -ExcludeProperty ("/.*") | Where-Object -Property "service" -EQ "service_name" | select ip_prefix
foreach ($awsip in $AWSIPs){
echo $awsip
}

This returns a list of IPs in this manner: - 0.0.0.0/00

  • 0.0.0.0/00
  • 0.0.0.0/00
  • 0.0.0.0/00
  • 0.0.0.0/00
  • 0.0.0.0/00

I need to use this list of IPs, however before I can do so I need to remove the /00 at the end (obviously that's not 00 but it's the subnet mask, which is rarely ever identical).

I'd greatly appreciate help with this.

Thanks.

1 Answer 1

4

A -replace-based solution:

$ips =  '0.0.0.0/00',
        '0.0.0.1/01',
        '0.0.0.2/02',
        '0.0.0.3/03',
        '0.0.0.4/04'

$ips -replace '(.*)/.*', '$1'

Note how you can use an array directly as the LHS of the -replace operation.

The above yields:

0.0.0.0
0.0.0.1
0.0.0.2
0.0.0.3
0.0.0.4

-split is an option too, but to avoid additional complexity you need an explicit loop:

foreach ($ip in $ips) {
  ($ip -split '/')[0]
}

It is possible to avoid an explicit loop, but that's probably not worth doing - for reasons of both performance and readability; it does show PowerShell's flexibility, however:

($ips -split '/')[(0..($ips.Count-1)).ForEach({ $_ * 2 })]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.