I want to get app insights of all the subscriptions available in the portal but whenever I run the script
$resources = az monitor app-insights component show | ConvertFrom-Json
I get app insights only for the same subscription every time , even during the time when I change the subscription through the script
Set-AzContext -SubscriptionName "some-name"
the whole script goes like this
Set-AzContext -SubscriptionName "some-name"
$resources = az monitor app-insights component show | ConvertFrom-Json
So even if I change the subscription name to something else suppose "some-name1"
still I am getting the app-insights for subscription "some-name"
2
Answers
This is by design.
While you could switch the context in a script, searches across multiple subscriptions are easier and much, much faster using the Resource Graph.
PowerShell Query:
Azure CLI Query:
Both options should get you all Application Insights resources across your tenant.
For more details, please see the Starter Resource Graph query samples.
On a side note I would also recommend to stick to either Azure CLI or Az PowerShell. While the choice of language is personal preference, sticking to one of the two decreases the dependencies. If you stick to Azure CLI, the only prerequisite is having the Azure CLI binaries installed. If you stick to Az Modules in PowerShell, you don’t need Azure CLI but only the Az Modules. Mixing both makes the code more difficult to port to other machines.
So, if using the Az Modules was preferred, instead of…
I would recommend:
The issue you’re experiencing with the
Set-AzContext
command is that it only sets the subscription context for the current PowerShell session.The
az monitor app-insights component show
command is running in a separate process or thread, so it is not able to see the updated subscription context set by theSet-AzContext
command.To work around this, you can pass the
-Subscription
parameter to theaz monitor app-insights component show
command, like so:This will ensure that the
az
command is running with the correct subscription context, and you will get the app insights for the correct subscription.