2

I have to iterate over a large loop of IPs and I have been able to do this with ease in bash, but while attempting to do this in PowerShell I found that I have little idea how to do something similar.

In bash I have done the following:

for ip in 10.98.{7..65}.{0..255}; do 
    echo "some text and a $ip";
done

However, in PowerShell I have done the following:

$ipprefix='10.98';
For ($i=7; $i -le 65; $i++) {
    For ($j=0; $j -le 255; $j++) {
        Write-Host "some text and a $ipprefix.$i.$j";
    }
}

Is there an easier way to do this in PowerShell?

1
  • I think what you are actually using there in bash is a glob. I have no idea whether PS globs are as powerful, but I think that's what you'd want to be googling, not "regex" Commented Dec 8, 2017 at 23:55

1 Answer 1

4

Ideally, the bash code has to unroll two loops, so the PowerShell you have is fundamentally the same. That said, you could nest two ranges in Powershell to achieve the same.

For example:

1..3 | % {$c = $_; 4..6 | % {$d = $_; Write-Host "a.b.$c.$d"}}

Gives:

a.b.1.4
a.b.1.5
a.b.1.6
a.b.2.4
a.b.2.5
a.b.2.6
a.b.3.4
a.b.3.5
a.b.3.6

From this, you can adapt to your problem above.

You could shorten this a bit if you wanted, and lose some readability like:

1..3 | % {$c = $_; 4..6 | % {Write-Host "a.b.$c.$_"}}
Sign up to request clarification or add additional context in comments.

2 Comments

There's also foreach($i in 7..65){foreach($j in 0..255){Write-Host "$i.$j"}}
Awesome! Thanks for your time.

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.