Azure / Azure/azure-powershell

Azure Session Context getting incorrectly applied to multiple instances of Foreach-Object -Parallel

Open
#10,349 7 comments 2 reactions 1 assignee Claimed by @wyunchi-ms View on GitHub
Azure PS Team bug customer-reported
Dominant language
C#
Stars
4.8k
Forks
4.3k
Avg merge
3d 14h
Merged PRs (30d)
54

Description

Hello, I am currently working on some Azure scripts where I need to perform a series of operations on each of the subscriptions under our tenant. I encountered a large problem when using Foreach-Object -Parallel. After some debugging I came up with this short script as a means of reproducing the issue.

```powershell
$subscriptiondata = Get-AzSubscription
$subscriptiondata | Foreach-Object -parallel {
$log = "Creating file for subscription $($_.name)..." | Out-File -FilePath` `"C:\temp\test\$($_.name).txt" -Force
$log = "Setting the session context to subscription $($_.name)..." | Out-File -FilePath` `"C:\temp\test\$($_.name).txt" -Force -Append
Set-AzContext -Name $_.name -Subscription $_.id -Force
$context = Get-AzContext
$log = "The context has been set to $($context.Subscription.Name)" | Out-File -FilePath` `"C:\temp\test\$($_.name).txt" -Force -Append
$Array = @(1..50)
Foreach ($number in $array){
$context = Get-AzContext
$log = "The context has been set to $($context.Subscription.Name)" | Out-File -FilePath` `"C:\temp\test\$($_.name).txt" -Force -Append
}
} -ThrottleLimit 10
```

(Apologies for the poor formatting of the script above - github keeps screwing with it)

The above script proves that for some reason, the Azure session context is not getting applied correctly to individual parallel sessions and seems to somehow be "leaking" from its original session to the others. Quite problematic, as it forces us abandon the parallel processing for this particular script. I hope this can get resolved in the future releases.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.