2 years ago

#14890

test-img

Bombbe

foreach loop issues in Azure Powershell Runbook

I have following code to loop all my vms in all subscriptions but for some reason Runbook never goes to my loop and therefore does nothing. This managed identity has VM contributors role from the root so permission is not the issue right now.

# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process | Out-Null

Write-Output "Connecting to azure via  Connect-AzAccount -Identity" 
Connect-AzAccount -Identity 
Write-Output "Successfully connected with Automation account's Managed Identity" 

Set-AzContext -SubscriptionId "0000-xxxx"

$Subscriptions = Get-AzSubscription
foreach ($sub in $Subscriptions) {
    # suppress output on this line
    Write-Host Working with Subscription $sub.Name 
    $null = Get-AzSubscription -SubscriptionName $sub.Name | Set-AzContext
    
    $vms = Get-AzVM

    foreach ($vm in $vms) {

        Write-Host Working with virtual Machine $vm.Name in resource group $vm.ResourceGroupName 

        stop-azvm -Name $vm.Name -ResourceGroup $vm.ResourceGroupName 
    }
}

If I put Get-AzVM or Get-AzSubscription command before loop it will show all my subscriptions or vms that are in context subscriptions so I know the commands work.

Script usually run like 5 minutes and then just goes to complied without doing really anything.

If I run the code from my computer in Visual Studio Code it goes fine trough but now am I missing now.

enter image description here

powershell

azure-automation

azure-runbook

0 Answers

Your Answer

Accepted video resources