Sunday, December 11, 2022

Pulling list of Azure servers

 Greetings everyone!

Sorry for the delay but I had either a cold, the flu, or, possibly, the plague.  But I am back with another terrific script from my good friend, Ross Jurek.

Ross created a script that will gather all Azure subscriptions, based on your Azure account, and list the virtual machines for each subscription.  The following information is retrieved:
Name
OS
Location
The state of the VM

Here is the script:

Connect-AzAccount -Verbose -Tenant <your tenant ID> 

$VMReport = @()
#Get All Subscriptions
$subs = Get-AzSubscription 
#Arry to store list of VMs
$vmobjs = @()
#loop through each subscription

foreach ($sub in $subs)
{
#Display the current processing subscription
Write-Host "Processing subscription $($sub.Name)"
    try
    {
    #Select the subscription
    #please add the condition if you want to skip a particular subscription

    Select-AzSubscription -SubscriptionId $sub.SubscriptionId -ErrorAction Continue

    #Get all the VMs information
    $vms = Get-AzVm 

     #loop through all the VMs
        foreach ($vm in $vms)
        {
            $PowerState = Get-AzVM  -Name $vm.Name -Status | select-object PowerState
            $vm.Name , $vm.StorageProfile.OsDisk.OsType , $vm.Location , $PowerState.PowerState
            $VMReport += New-Object psobject -Property @{
            "VMName" = $vm.Name
            "VMOSType" = $vm.StorageProfile.OsDisk.OsType
            "VMLocation" = $vm.Location
            "VMState" = $PowerState.PowerState
            }
        }
    }
    catch
    {
        Write-Host $error[0]
    }

}

#export to csv format
Remove-Item c:\temp\AzureServerList.csv -ErrorAction Ignore
$VMReport | Export-Csv "c:\temp\AzureServerList.csv"

Disconnect-AzAccount

I have a Virtual Studio subscription and I didn't want that information to be part of the output.  I made the following change to the $subs = Get-AzSubscription command
$subs = Get-AzSubscription | where-object { $_.Name -like "My Cloud*"}

I had an issue when I first tried the script.  I kept getting the following message for each VM:
WARNING: There are more than 100 VMs in the result.  Only the statuses of 100 VMs are shown to avoid throttling.  To get the actual status of each VM, please provide a VM name with -Status parameter.

I talked with Ross about this and he recommended I either install or upgrade my Az module.  So, if you get the error, try either of the following:
install-module -name Az -RequiredVersion 9.1.1
update-module -name Az -RequiredVersion 9.1.1

Again, I want to thank Ross Jurek for sharing this code with us.

Please leave a comment if you have any questions feedback.

Until next time...

No comments:

Post a Comment