首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PowerShell 7.ForEach-对象-Parallel不针对Azure PowerShell进行身份验证

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

Stack Overflow用户
提问于 2021-07-01 21:40:10
回答 1查看 92关注 0票数 5

我们写了一个脚本,它应该并行执行Azure PowerShell命令。问题是,当我们将-ThrottleLimit增加到大于1的时候,一些命令不能正确执行。脚本是:

代码语言:javascript
复制
# 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

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

这种行为的原因是什么?

EN

回答 1

Stack Overflow用户

发布于 2021-07-12 17:55:58

简而言之,-Parallel参数并不(可能)神奇地导入属于For-EachObject块作用域的所有依赖变量。实际上,PWSH跨越不同的进程,只有被循环的数组才会被隐式传递,所有其他变量都需要显式指定。

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

示例:

代码语言:javascript
复制
$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.*
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68211301

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档