AZ CLIPowerShell

AZ CLI (Resource Graph) – To retrieve azure virtual machine information with power status.

I was developing a solution to fetch azure VM information as part of the update management process. Indeed, there are many ways to pull the reports. But, I thought of doing it in az cli is best options! Here is the script which pulls out the azure virtual machines information with power status.

$virtualMachines = az.cmd graph query -q "where type =~ 'Microsoft.Compute/virtualMachines' | extend aliases | project id, sku = tostring(aliases['Microsoft.Compute/imageSku']), offer = tostring(aliases['Microsoft.Compute/imageOffer']) , publisher = tostring(aliases['Microsoft.Compute/imagePublisher']) | where offer == 'WindowsServer'" --first 200 | ConvertFrom-Json
$groupBy = 40
$resultCollection = @()
$group = [math]::Ceiling($virtualMachines.Count / $groupBy)
for ($i = 0; $i -le $group; $i++)
    $start = $i * $groupBy
    $end = (($i + 1) * $groupBy) - 1
    "Processing for $($start) .. $($end)"
    $resultCollection += @(az.cmd vm get-instance-view --ids $($virtualMachines[$start..$end].id)) | ConvertFrom-Json

That’s the first cut of scripts which worked as expected – There are some good and bad in the preceding code.

Good: It just works!

Bad: It’s ugly

Working on alternatives!



Leave a Reply

Your email address will not be published. Required fields are marked *