Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: How to add Result to an Array (ForEach-Object -Parallel)

Tags:

powershell

I know, that with the Parameter $using:foo I can use a Variable from a different runspace while running ForEach-Object -Parallel in Powershell 7 and up.

But how can I add the result back to a Variable? The common parameters += and $using: will not work.

For instance:

$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.
like image 546
Gill-Bates Avatar asked Jun 25 '26 04:06

Gill-Bates


1 Answers

You will have to split the operation into two and assign the reference you get from $using:Costs to a local variable, and you will have to use a different data type than PowerShell's resizable array - preferably a concurrent (or thread-safe) 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))
}
like image 76
Mathias R. Jessen Avatar answered Jul 02 '26 06:07

Mathias R. Jessen