skip to Main Content

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


  1. 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:

    Search-AzGraph -Query "resources | where type =~ 'Microsoft.Insights/components'"
    

    Azure CLI Query:

    az graph query -q "resources | where type =~ 'Microsoft.Insights/components'"
    

    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…

    $resources =  az monitor  app-insights component show | ConvertFrom-Json
    

    I would recommend:

    $resources = Search-AzGraph -Query "resources | where type =~ 'Microsoft.Insights/components'"
    
    Login or Signup to reply.
  2. 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 the Set-AzContext command.

    To work around this, you can pass the -Subscription parameter to the az monitor app-insights component show command, like so:

    $resources = az monitor app-insights component show --subscription "some-name1" | ConvertFrom-Json
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search