PowerShell 7. ForEach-Object -Parallel 不会针对 Azure PowerShell 进行身份验证

Win*_*oss 5 azure-powershell powershell-7.0

我们编写了一个脚本来并行执行 Azure PowerShell 命令。问题是当我们增加-ThrottleLimit大于 1 时,某些命令没有正确执行。脚本是:

# Writing IPs for whitelisting into file.
Add-Content -Path IPs.txt -Value ((Get-AzWebApp -ResourceGroupName "ResourceGroup1" -Name "WebApp1").OutboundIpAddresses).Split(",")
Add-Content -Path IPs.txt -Value ((Get-AzWebApp -ResourceGroupName "ResourceGroup1" -Name "WebApp1").PossibleOutboundIpAddresses).Split(",")
# Writing new file with inique IPs.
Get-Content IPs.txt | Sort-Object -Unique | Set-Content UniqueIPs.txt

# Referencing the file.
$IPsForWhitelisting = Get-Content UniqueIPs.txt

# Assigning priotiry number to each IP
$Count = 100
$List = foreach ($IP in $IPsForWhitelisting) { 
  $IP|Select @{l='IP';e={$_}},@{l='Count';e={$Count}}
  $Count++
}
# Whitelisting all the IPs from the list.
$List | ForEach-Object -Parallel {
    $IP = $_.IP
    $Priority = $_.Count
    $azureApplicationId ="***"
    $azureTenantId= "***"
    $azureApplicationSecret = "***"
    $azureSecurePassword = ConvertTo-SecureString $azureApplicationSecret -AsPlainText -Force
    $credential = New-Object System.Management.Automation.PSCredential($azureApplicationId , $azureSecurePassword)
    Connect-AzAccount -Credential $credential -TenantId $azureTenantId -ServicePrincipal | Out-null
    echo "IP-$Priority"
    echo "$IP/24"
    echo $Priority
    Add-AzWebAppAccessRestrictionRule -ResourceGroupName "ResourceGroup1" -WebAppName "WebApp1" -Name "IP-$Priority" -Priority $Priority -Action Allow -IpAddress "$IP/24"
} -ThrottleLimit 1
Run Code Online (Sandbox Code Playgroud)

如果ThrottleLimit设置为 1 - 8 条规则正在创建,如果ThrottleLimit设置为 2 - 7 条规则正在创建,3 - 4 条规则,10 - 1 条规则,因此一些规则被跳过。

这种行为的原因是什么?

小智 0

简而言之 --Parallel参数不会(但也许)神奇地导入属于For-EachObject块范围内的所有因变量。实际上,PWSH 跨越单独的进程,只有循环的数组才会被隐式传递,所有其他变量都需要显式指定。

应使用$using:指令(前缀)来表示要在并行代码块中导入(使其可见)的变量。

例子:

$avar = [Int]10
$bvar = [Int]20
$list = @('here', 'it', 'eees')

$list | ForEach-Object -Parallel {
    Write-Output "(a, b) is here ($($using:avar), $($using:bvar))"
    Write-Output "(a, b) missing ($($avar), $($bvar))"
    Write-Output "Current element is $_"
}```

*thus - the described behavior is likely due to the fact that config. variables are not imported (at all) and thus the operations silently fail.*
Run Code Online (Sandbox Code Playgroud)