Search code examples
azurepowershellcloud

Powershell script that gets the list of Windows VMs with a specific tag


using powershell, I need to get a list of Windows VMs of all subscriptions within a tenant. I need only the VMs with a tag ApplicationName that contains PROD in its value.

Here is my current script:

# Get resource groups with the specified tag
$resourceGroups = Get-AzResourceGroup | Where-Object { $_.Tags -ne $null -and $_.Tags['ApplicationName'] -like "*PROD*" }
 
# Create an array to store the results
$results = @()
 
# Iterate through each resource group
foreach ($group in $resourceGroups) {
    $groupName = $group.ResourceGroupName
    $vms = Get-AzVM

    foreach ($vm in $vms) {

        if ($vm.StorageProfile.OSDisk.OSType -eq "Windows") {

            $result = [ordered]@{
                'VM Name' = $vm.Name
                'Subscription' = $group.Subscription
                'Resource Group' = $groupName
                'Location' = $vm.Location
                'Publisher' = $vm.StorageProfile.ImageReference.Publisher
                'Plan' = $vm.StorageProfile.ImageReference.Sku
                'Offer' = $vm.StorageProfile.ImageReference.Offer
            }
        $results += New-Object -TypeName PSObject -Property $result
        }  
    }
}

# Output the results in a table format
$results | Format-Table -AutoSize
 
# Export the results to a CSV file
$results | Export-Csv -Path "C:\Users\XXXXXXXXXX\WindowsVMsList.csv" -NoTypeInformation
 
Write-Output "Script execution completed."

There are 2 issues in the script output, subsription column is blank and the ApplicationName tag filter is not taked in consideration.

Any help please?


Solution

  • I need to get a list of Windows VMs of all subscriptions within a tenant. I need only the VMs with a tag ApplicationName that contains PROD in its value.

    Here is the updated PowerShell script to fetch all VMs in the tenant that are tagged with the specified tags.

    $vmList = @()
    
    $sub = Get-AzSubscription
    
    foreach ($subnames in $sub) {
      $subid = $subnames.Id
        Set-AzContext -SubscriptionId $subId
        $vms = Get-AzVM | Where-Object { $_.StorageProfile.OsDisk.OsType -eq "Windows" -and $_.Tags["ApplicationName"] -like "*PROD*" }
        foreach ($vm in $vms) {
           $subId = $vm.Id.Split('/')[2]
            $vmList += [PSCustomObject]@{
                Name = $vm.Name
                SubscriptionID = $subId
                ResourceGroup = $vm.ResourceGroupName
                Location = $vm.Location
                OsProfile = $vm.OsProfile
                VMTags = $vm.Tags
            }
        }
    }
    $vmList 
    
    $vmList | Export-Csv -Path "C:\Users\XXXXX\WindowsVMsList.csv" -NoTypeInformation
    

    Output

    enter image description here