Powershell:如何将结果添加到数组(ForEach-Object -Parallel)

2023-12-29

我知道,用参数$using:foo我可以在运行时使用来自不同运行空间的变量ForEach-Object -Parallel在 Powershell 7 及更高版本中。

但是如何将结果添加回变量呢?常用参数+= and $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
}

Output:

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 可调整大小的数组不同的数据类型 - 最好是同时 (or 线程安全) type:

$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))
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Powershell:如何将结果添加到数组(ForEach-Object -Parallel) 的相关文章

随机推荐