![](/img/trans.png)
[英]How is the new PowerShell 7 ForEach-Object Parallel implemented?
[英]Powershell: How to add Result to an Array (ForEach-Object -Parallel)
我知道,通过参数$using:foo
我可以在 Powershell 7 及更高ForEach-Object -Parallel
中运行ForEach-Object -Parallel
时使用来自不同运行空间的变量。
但是如何将结果添加回变量? 通用参数+=
和$using:
将不起作用。
例如:
$AllSubs = Get-AzSubscription
$Date = (Get-Date).AddDays(-2).ToString("yyyy-MM-dd")
$Costs = @()
$AllSubs | Sort-Object -Property Name | ForEach-Object -Parallel {
Set-AzContext $_.Name | Out-Null
Write-Output "Fetching Costs from '$($_.Name)' ..."
$using:Costs += Get-AzConsumptionUsageDetail -StartDate $using:Date -EndDate $using:Date -IncludeAdditionalProperties -IncludeMeterDetails -ErrorAction SilentlyContinue
}
输出:
The assignment expression is not valid. The input to an assignment operator must be an object that is
| able to accept assignments, such as a variable or a property.
您必须将操作拆分为两个并将从$using:Costs
获得的引用分配给局部变量,并且您必须使用与 PowerShell 的可调整大小的数组不同的数据类型 - 最好是并发(或线程安全)类型:
$AllSubs = Get-AzSubscription
$Date = (Get-Date).AddDays(-2).ToString("yyyy-MM-dd")
# Create thread-safe collection to receive output
$Costs = [System.Collections.Concurrent.ConcurrentBag[psobject]]::new()
$AllSubs | Sort-Object -Property Name | ForEach-Object -Parallel {
Set-AzContext $_.Name | Out-Null
Write-Output "Fetching Costs from '$($_.Name)' ..."
# Obtain reference to the bag with `using` modifier
$localCostsVariable = $using:Costs
# Add to bag
$localCostsVariable.Add($(Get-AzConsumptionUsageDetail -StartDate $using:Date -EndDate $using:Date -IncludeAdditionalProperties -IncludeMeterDetails -ErrorAction SilentlyContinue))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.