The Azure CLI is a cross-platform, open-source command-line tool that we may use to build and manage resources in the Azure Portal. This application allows us to issue commands and manage Azure resources directly from the Windows Powershell.
we can simply install azure cli in a windows computer from the following commands using cmd
Set-ExecutionPolicy RemoteSigned
Install-Module -Name Az -AllowClobber
once you have installed, just configure cli with your azure credentials by following command
Connect-AzAccount
use the following command to select active subscription for azure cli
Select-AzSubscription -SubscriptionName Your Subscription Name
refer and use the following script for tag replication for selected subscription appropriately
# Get the list of virtual machines
$vms = Get-AzVM
# Loop for each virtual machine
foreach ($vm in $vms) {
# Get VM details
$vmResourceGroup = $vm.ResourceGroupName
$vmName = $vm.Name
$vmId = $vm.Id
Write-Host "get VM: $vmName in RG: $vmResourceGroup"
# Get VM Tags
$vmTags = (Get-AzResource -ResourceGroupName $vmResourceGroup -ResourceName $vmName -ResourceType "Microsoft.Compute/virtualMachines").Tags
# Get the VM's disk resource ids
$diskIds = Get-AzDisk | Where-Object { $_.ManagedBy -eq $vmId } | Select-Object -ExpandProperty Id
# Update tags for disks
foreach ($diskId in $diskIds) {
Write-Host "Applying tags to Disk: $diskId"
Update-AzTag -ResourceId $diskId -Tag $vmTags -Operation Merge
}
# Get the VM's NIC (Network Interface) resource ids
$nicIds = $vm.NetworkProfile.NetworkInterfaces.Id
# Apply VM Tags to all NICs
foreach ($nicId in $nicIds) {
Write-Host "Applying tags to NIC: $nicId"
Update-AzTag -ResourceId $nicId -Tag $vmTags -Operation Merge
}
Write-Host "Completed VM: $vmName"
}