PowerShell。增加ForEach对象中的计数-并行

PowerShell。增加ForEach对象中的计数-并行,powershell,Powershell,我想使用ForEach对象-与Azure Web应用的白名单IP并行。这通常是这样做的: Add-AzWebAppAccessRestrictionRule -ResourceGroupName "ResourceGroup1" -WebAppName "WebApp1" -Name "IP-100" -Priority "100" -Action Allow -IpAddress "10.0.0.0/24

我想使用ForEach对象-与Azure Web应用的白名单IP并行。这通常是这样做的:

Add-AzWebAppAccessRestrictionRule -ResourceGroupName "ResourceGroup1" -WebAppName "WebApp1" -Name "IP-100" -Priority "100" -Action Allow -IpAddress "10.0.0.0/24"
foreach($IP in $IPs1)
{
  Add-AzWebAppAccessRestrictionRule -ResourceGroupName "ResourceGroup1" -WebAppName "WebApp1" -Name "IP-$name" -Priority "$priority" -Action Allow -IpAddress "$IP/24"
  $name ++
  $priority ++
}
我想到的改变计数的方法,如将IP-100更改为IP-101,优先级从100更改为101不起作用,因为
ForEach Object-Parallel
正在使用:

每个运行空间必须加载所需的任何模块,并且具有任何 变量不能从调用脚本显式传入。唯一的 自动出现在并行脚本块中的变量为 管道输入对象

我如何并行运行这样的脚本,类似这样的东西

$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
没有平行,我通常是这样做的:

Add-AzWebAppAccessRestrictionRule -ResourceGroupName "ResourceGroup1" -WebAppName "WebApp1" -Name "IP-100" -Priority "100" -Action Allow -IpAddress "10.0.0.0/24"
foreach($IP in $IPs1)
{
  Add-AzWebAppAccessRestrictionRule -ResourceGroupName "ResourceGroup1" -WebAppName "WebApp1" -Name "IP-$name" -Priority "$priority" -Action Allow -IpAddress "$IP/24"
  $name ++
  $priority ++
}

一种简单的方法是在将每个IP传递给并行
ForEach
循环之前为其分配一个优先级:

$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
然后,您只需运行您已经拥有的:

$list | ForEach-Object -Parallel {
    Add-AzWebAppAccessRestrictionRule -ResourceGroupName "ResourceGroup1" -WebAppName "WepApp1" -Name "IP-$($_.Priority)" -Priority $_.Priority -Action Allow -IpAddress "$($_.IP)/24" -WhatIf
}

在应用设置之前,请尝试为每个条目构建一个哈希表,例如,
Get Content UniqueIPs.txt | foreach object-begin{$count=1};{@{“ip”=$\u;“priority”=$count};count++;}
然后将其导入并行foreach。您已经知道每个条目的优先级,而不必跟踪并行循环中的计数器。。。