How to run Powershell script on multiple Subscriptions Using Az PowerShell Command - azure

I have multiple azure tenants, each having multiple subscriptions, and I have to run a single PowerShell script for all my subscriptions.
This can be achieved using Azure CLI, and it works perfectly.
I use Azure CLI as below;
$az_account = (az account list --query "[].[name]" -o tsv)
foreach ($account in $az_account) {
az account set --name $account
#<RUN SCRIPTS HERE>#
}
But in some situations, I have to use the Az PowerShell command instead of Azure CLI.
So could anyone help me
How to run Az PowerShell commands for multiple subscriptions
Or the Az PowerShell profile file path ( same as Azure CLI which is C:\Users\%USER\.Azure\azureProfile.json ).

How to run Az PowerShell commands for multiple subscriptions
You can use the below PowerShell Scripts to run the multiple subscription PowerShell commands.
# Get the Subscription Details using Get-AzSubscription Command
Get-AzSubscription | ForEach-Object {
# Set the context Details using Set-AzContext Command which is equalent to the az account set CLI Command
$_ | Set-AzContext
$subscriptionName = $_.Name
#<RUN YOUR SCRIPTS HERE>#
}
Or the Az PowerShell profile file path ( same as Azure CLI which is C:\Users\%USER\.Azure\azureProfile.json ).
Refer here for profile file path location

Resolution
After a couple of tries, finally found some methods to solve my issue. posting the same here might be helpful for someone.
You can connect all the subscriptions using the below commands
Connect-AzAccount -Tenant "xxxx-xxxxx-xxxx-xxx" -Subscription "xxxx-xxxxx-xxxx-xxx"
To List all the connected subscriptions
Get-AzContext -ListAvailable | Select-Object Name, Subscription, Tenant
If you want to rename to a friendly Name,
Rename-AzContext -SourceName "Azure subscription 1 (xxxxx-xxxx-xxxx-xxxx-xxxx) - xxxxx-xxxx-xxx-xxxx-xxxx-xxx - jawad#xyz.com" -TargetName "MySubscription"
To save these profiles to file,
Save-AzContext -Path "C:\Users\jawad\Downloads\AzpwshProfile.json"
You can import any time these profiles using the below command, (test first clear the profile Clear-AzContext -Force)
Import-AzContext -Path "C:\Users\jawad\Downloads\AzpwshProfile.json"
Now you easily use for loop to set the subscriptions, for example
$acc = (Get-AzContext -ListAvailable | Select-Object Name)
foreach ($account in $acc) {
>> Select-AzContext $account.Name
>> Get-AzVM | Export-Csv -Path "inventory.csv"
>> }
Thank you

Related

New automation variable by cli or ansible

After create a runbook and edit content, I want to create variable and set value for them. How can I do it by ansible or azure cli ?
Please help me
Azure Automation stores each encrypted variable securely. When you create a variable, you can specify its encryption and storage by Azure Automation as a secure asset.
You must set the value with the Set-AzAutomationVariable cmdlet or the internal Set-AutomationVariable cmdlet. You use the Set-AutomationVariable in your runbooks that are intended to run in the Azure sandbox environment, or on a Windows Hybrid Runbook Worker.
You can create variables and set value for them using PowerShell script.
$rgName = "ResourceGroup01"
$accountName = "MyAutomationAccount"
$vm = Get-AzVM -ResourceGroupName "ResourceGroup01" -Name "VM01" | Select Name, Location,Extensions
New-AzAutomationVariable -ResourceGroupName "ResourceGroup01" -AutomationAccountName "MyAutomationAccount" -Name "MyComplexVariable" -Encrypted $false -Value $vm
$vmValue = Get-AzAutomationVariable -ResourceGroupName "ResourceGroup01" -AutomationAccountName "MyAutomationAccount" -Name "MyComplexVariable"
$vmName = $vmValue.Value.Name
$vmTags = $vmValue.Value.Tags
Reference: Manage variables in Azure Automation | Microsoft Docs

Powershell Script to download Azure recommendations

Login-AzAccount
$subs= az account list --query '[*].id'
Get-AzAdvisorRecommendation list --subscription $subs
I need to download the list of Azure recommendations on a tenant which will be having multiple subscriptions using Powershell script
Get-AzAdvisorRecommendation list --subscription $subs
Instead of --subscription you need to pass -subscription as a parameter to Get-AzAdvisorRecommendation cmdlet.
As per the Azure PowerShell cmdlet documentation, The Cmdlet Get-AzAdvisorRecommendation doesnt have any flag -subscription as parameter.
You can use this below script to pull the azure advisor recommendations for all subscriptions under a particular tenant.
$list=#()
$sub=get-azsubscription
Write-Output $sub
foreach( $item in $sub){
Set-AzContext -Subscription $item.Id -Tenant $item.TenantId -Force
$rg=Get-AzResourceGroup
foreach($r in $rg){
$list+=Get-AzAdvisorRecommendation -ResourceGroupName $r.ResourceGroupName
}
}
$list | Export-Csv C:\Users\list.csv
Here is the sample output for reference:
While testing the above script in our local environment, we have passed a single subscription to the cmdlet Get-azsubscription using the -subscriptionId flag.
Using this updated script, I can download the recommendations as well, thanks Venkatesh for your inputs.
Login-AzAccount
$result= 'C:\Users\new.csv'
$list=#()
$subs=get-AzSubscription
foreach( $sub in $subs){
Set-AzContext -Subscription $sub.Id -Force
$list+=Get-AzAdvisorRecommendation | Select-Object category, Impact, #{Name="SubscriptionName"; Expression={$sub.name}}, #{Name="SubscriptionID";
Expression={$sub.Id}}, #{Name="Recommendation"; Expression=$_.ShortDescription.Problem}}, ImpactedField, ImpactedValue,RecommendationTypeId, LastUpdated, MetaData, SuppressionId, Name,
resourceid
}
$list | Export-Csv $result -NoTypeInformation

How to filter resources using more than one tag using azure CLI?

I can able to get the resource details by using the tag using the Azure CLI command
az resource list --tag AppID=XXXX --query [].name
However, how can filter resources use more than one tag? Could you please help?
Example:
az resource list --tag AppID=XXXX, Region=DEV --query [].name
Based on the above requirement we have created a script using both Azure CLI cmdlets & PowerShell cmdlet to filter the resources using more than one Tag.
Script using PowerShell Cmdlet:
connect-azaccount
$resource = Get-AzResource -ResourceGroupName <resourcegroupName> -TagName env -TagValue prod |Select-Object -Property ResourceId
$resourcearray=$resource
foreach ( $resource in $resourcearray){
$Tagvalue=(Get-AzTag -ResourceId $resource.ResourceId)
if ($Tagvalue.Properties.TagsProperty.Count -gt 1)
{
$Tagvalue.Id -replace "/providers/Microsoft.Resources/tags/default",""
}
}
Here is the output for reference :
Script using Azure CLI cmdlets:
$re= az resource list --tag env=prod
$rearray = $re |ConvertFrom-Json
foreach ( $re in $rearray)
{
$tagcount=$(az tag list --resource-id $re.id --query "properties.tags|length(#)")
if ($tagcount -ge 1)
{
$re.id
}
Here is the output for reference :

How can i stop and start a logic app on azure using powershell?

I want to stop and start ie restart a logic app on Azure using Powershell
I have looked at the documentation and it shows the following:
Stop-AzureRmLogicAppRun -ResourceGroupName "ResourceGroup11" -Name
"LogicApp03" -RunName "08587489104702792076" -Force
But where can i find the -RunName on Azure ?
Runs appears in the Runs history:
The RunName is just the run identifier.
So you can get it from azure portal or you can get runs history using powershell with Get-AzureRmLogicAppRunHistory (or Get-AzLogicAppRunHistory if you're using the new az powershell module).
To get all the Running runs, you can try this command:
Get-AzureRmLogicAppRunHistory -ResourceGroupName <rg name> -Name <logicapp name> | Where {$_.Status -eq 'Running'}
Also if you want to disable a logic app, you use this command:
Set-AzureRmLogicApp -ResourceGroupName <rg name> -Name <logicapp name> -State "Disabled"

Install extension on both Classic and ARM VMs with single PowerShell command

I have a script that installs OMS extensions to all ARM VMs in the subscription. The problem is that I have subscriptions that contain only ARM VMs, subscriptions that contain only Classic VMs, and subscription that have both types of VMs. How can I modify the script to work in all of the conditions? The script is:
#This script installs OMS Monitoring Agent to all VMs in the selected Subscription.
#Before running this script, the user must login to Azure account and select target subscription.
#Example:
#Login-AzureRmAccount
#Select-AzureRmSubscription 'SubscriptionName'
$WorkspaceID = 'Provide Workspace ID here'
$WorkspaceKey = 'Provide Workspace key here'
$VMs = Get-AzureRmVM
$VMs.where({$_.osprofile.windowsconfiguration}) | ForEach-Object {
"Installing Microsoft.EnterpriseCloud.Monitoring.MicrosoftMonitoringAgent Extension: {0}" -f $_.id
Set-AzureRmVMExtension -ResourceGroupName $_.ResourceGroupName -VMName $_.Name -Name omsAgent -Publisher 'Microsoft.EnterpriseCloud.Monitoring' `
-ExtensionType 'MicrosoftMonitoringAgent' -AsJob -TypeHandlerVersion '1.0' -Location $_.Location -ForceRerun 'yesh' `
-SettingString ( "{'workspaceId': '$WorkspaceID'}") `
-ProtectedSettingString "{'workspaceKey': '$WorkspaceKey'}" |
Add-Member -Name VM -Value $_.Id -MemberType NoteProperty
}
Since you got both classic and ARM VMs, you got two different deployment models, hence two different PowerShell modules you are using.
In other words, you need to log in separately for each and have separate scripts for using them.
In the classic model you need to run the following cmdlet to login and access your VMs:
Add-AzureAccount
Get-AzureVM | Set-AzureVMExtension ``
-Publisher 'Microsoft.EnterpriseCloud.Monitoring' ``
-ExtensionName 'MicrosoftMonitoringAgent' ``
-Version '1.*' ``
-PublicConfiguration "<workspace id>" ``
-PrivateConfiguration "<workspace key>" ``
While searching for information I found this script. It's a script for on-boarding VMs from single, or multiple subscriptions, using both deployment models.

Resources