Shepard
Shepard

Reputation: 1

Azure runbook foreach loop

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

Upvotes: 0

Views: 535

Answers (1)

Shepard
Shepard

Reputation: 1

Gave the RunAs account access to all of the required subscriptions. This allowed the foreach loop to run through all of the subscriptions instead of just the one where the Automation account is.

Upvotes: 0

Related Questions