Reputation: 978
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?
Upvotes: 2
Views: 67
Reputation: 7153
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.$_"}}
Upvotes: 4