Michal Checinski

Trigger Azure Policy scan on multiple subscriptions

November 19, 2021 , posted under Azure Azure Policy Script Governance
Trigger Azure Policy scan on multiple subscriptions

When testing Azure Policies one of the problems may be that the policy evaluation takes a really long time to scan all resources across all subscriptions in the scope of the particular Azure Policy.

In this short post, I want to give you a simple script that will trigger immediate policy scan for all of the subscriptions assigned to your account.


To now waste your time, I’m going to present you the script. Down below in the next section of this article, you can find a deeper explanation of it if you want to know how it works.

Before using it, you need to login to your Azure Account using az login command (with optional -t parameter followed with a tenant id if you want to authorize against a particular tenant of your account).

So here goes the script:

$subscriptions=$(az account subscription list --query [].subscriptionId | ConvertFrom-Json)
Foreach ($sub in $subscriptions)
    Write-Host "Setting subscription to $sub ..."
    az account set -s $sub
    Write-Host "Triggering scan on subscription $sub ..."
    az policy state trigger-scan
    Write-Host "Finished scan on subscription $sub."
    Write-Host "------------------------------------------------------------------------"


The script uses the preview (as of 11/2021) command group account subscription to list all subscriptions, with --query parameter, using which we can alter the output to the desired information. In this case, we need only the subscriptionId json property from the list of subscriptions. I’m using then the pipeline to pass the output of this command to the ConvertFrom-Json powershell command which well, converts the outputted json array to powershell array. This array is saved to the $subscriptions variable.

Then foreach loop is used to iterate through every subscription id from the $subscriptions variable. The command az account set is used to switch to the subscription using subscription id. The az policy state trigger-scan command is the star of the show, as this command triggers the policy scan on currently selected subscription (it’s done in the previous step). The actual

All of those actions are surrounded by Write-Host commands to give the user a visible status of the task that the script is currently performing.

The script is simple but powerful. You don’t need now to cycle manually through all of the subscriptions. You can run it, and save yourself a bit of time when evaluating the compliance status of the Azure Policies.