2

I'd like to use ForEach-Object -Parallel to whitelist IPs for Azure Web Apps. This is normally done like this:

Add-AzWebAppAccessRestrictionRule -ResourceGroupName "ResourceGroup1" -WebAppName "WebApp1" -Name "IP-100" -Priority "100" -Action Allow -IpAddress "10.0.0.0/24"

The approach that I had in mind, with changing count, as in changing IP-100 to IP-101, Priority from 100 to 101 doesn't work, as ForEach-Object -Parallel is using isolated runspaces:

Each runspace must load whatever module is needed and have any variable be explicitly passed in from the calling script. The only variable that automatically appears in the parallel script block is the piped in object.

How can I run such script in parallel, something like this?

$Count = 100
Get-Content UniqueIPs.txt | ForEach-Object -Parallel {
    Add-AzWebAppAccessRestrictionRule -ResourceGroupName "ResourceGroup1" -WebAppName "WepApp1" -Name "IP-$using:Count" -Priority "$using:Count" -Action Allow -IpAddress "$IP/24" -WhatIf
    $Count ++
} -ThrottleLimit 5

Without -Parallel I usually did it like this:

foreach($IP in $IPs1)
{
  Add-AzWebAppAccessRestrictionRule -ResourceGroupName "ResourceGroup1" -WebAppName "WebApp1" -Name "IP-$name" -Priority "$priority" -Action Allow -IpAddress "$IP/24"
  $name ++
  $priority ++
}
WinBoss
  • 879
  • 1
  • 17
  • 40
  • 2
    Try building a hashtable for each entry *before* you apply the settings - e.g. ```Get-Content UniqueIPs.txt | foreach-object -begin { $count = 1}; { @{"ip"=$_; "priority"=$count}; count++; }``` and then piping **that** into your parallel foreach. You already know the priority of each entry then without having to track a counter in the parallel loop... – mclayton Mar 29 '21 at 14:19

1 Answers1

1

An easy way to do this is assign each IP a priority before passing it to your parallel ForEach loop:

$priority = 100
$IPs = '10.0.0.1','10.0.0.2','10.0.0.3'
$list = foreach ($IP in $IPs) { 
    $IP|select @{l='IP';e={$_}},@{l='Priority';e={$priority}}
    $priority++
}

# $list Outputs:
IP       Priority
--       --------
10.0.0.1      100
10.0.0.2      101
10.0.0.3      102

Then you just run what you have already:

$list | ForEach-Object -Parallel {
    Add-AzWebAppAccessRestrictionRule -ResourceGroupName "ResourceGroup1" -WebAppName "WepApp1" -Name "IP-$($_.Priority)" -Priority $_.Priority -Action Allow -IpAddress "$($_.IP)/24" -WhatIf
}
Cpt.Whale
  • 4,784
  • 1
  • 10
  • 16