Share via

Azure Runbook Foreach loop

Shepard 1 Reputation point
2021-07-12T15:55:25.137+00:00

I am running a for each loop in a Azure runbook to capture Policy exemptions into a csv file. It works locally in powershell but is not cycling through the loop when I am running it from a runbook. Any help would be much appreciated.

Here is the script...

$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzAccount -ServicePrincipal -Tenant $Conn.TenantID `
-ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint

$subscriptions=Get-AzSubscription
Write-Output $subscriptions
$storageAcct=New-AzStorageContext -StorageAccountName Accountname -StorageAccountKey "Key"
$azpolicylist="$Env:temp/PolicyList.csv"
$azpolicyExemption="$Env:temp/Exemptions.csv"

Remove-Item -Path $env:TEMP -Recurse -Force -ErrorAction SilentlyContinue
remove-azstorageblob -blob Exemptions.csv -Container "Name" -Context $storageAcct.context
remove-azstorageblob -blob PolicyList.csv -Container "Name" -Context $storageAcct.context

$starttime = Get-Date
$starttime.DateTime

forEach ($Subscription in $subscriptions){

set-AzContext $Subscription
Write-Output $Subscription

$policyassignment=get-azpolicyassignment | Select Name,ResourceID, SubscriptionID | Export-CSV $azpolicylist -Append -Force

$policyexemptions=get-azpolicyexemption | Select Name,ResourceID, SubscriptionID | Export-CSV $azpolicyExemption -Append -Force

Set-AzStorageBlobContent -File $azpolicyexemption -Container "Name" -BlobType "Block" -Context $storageAcct.context -Verbose -Force
Set-AzStorageBlobContent -File $azpolicylist -Container "Name" -BlobType "Block" -Context $storageAcct.context -Verbose -Force

}

$endtime = Get-Date
$endtime.DateTime
$runtimetotal = $endtime - $starttime
$a = "Operation took",$runtimetotal.TotalMinutes,"minutes to complete." -join " "
Write-Output $a
Write-Output System.log

Azure Automation
Azure Automation

An Azure service that is used to automate, configure, and install updates across hybrid environments.

0 comments No comments

1 answer

Sort by: Most helpful
  1. tbgangav-MSFT 10,431 Reputation points Moderator
    2021-07-14T09:51:14.477+00:00

    Hi @Shepard ,

    It looks like a duplicate of this question. Please refer it for detailed explanation.

    In short, provide permission to your Azure Automation run as account so that it can access policy details from other subscriptions.

    In local environment it worked because the login in local environment is different from run as account and that user with which you have logged in local environment, has access to all the other subscriptions.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.