I want to write a script (preferably PowerShell calling the Az cli modules) that lists of all Windows VMs (whether allocated or de-allocated), subscription, resource-group, vm-name, the os system, the OS version, latest patch information under all Azure subscriptions under a single Azure Tenant. Want this in table format.
There are a number of scripts on the internet but use the 'old' Az modules.
I need help in identifying the Az modules to use and fields to query.
My high level pseudo logic.
$tenant_id = xxxx-xxxx-xxxx-xxxx
$subscription_array = Get-All-Subcriptions -tenant $tenant_id
for(each $sub in $subscription_array)
{
$vm_array = Get-Windows-Vms -subscription $sub
for(each $vm in $vm_array)
{
$vm_name = $vm.name
$vm_os = $vm.os -- Windows-2019, Windows_server-2012 etc...
$vm_rg = $vm.resource_group
$vm_patch_version = $vm.latest_patch_no
$collection_of_vm_records.add($vm_name, $vm_os, $vm_rg, $vm_patch_version)
}
}
Write $collection_of_vm_records to csv file
CodePudding user response:
This will give you both windows and linux vm's details.
$report = @()
$subs = Get-AzSubscription
Foreach ($sub in $subs)
{
select-AzSubscription $sub | Out-Null
$subName = $sub.Name
$vms = Get-AzVM
$publicIps = Get-AzPublicIpAddress
$nics = Get-AzNetworkInterface | Where-Object { $_.VirtualMachine -NE $null}
foreach ($nic in $nics) {
$info = "" | Select-Object VmName, ResourceGroupName, Region, VmSize, VirtualNetwork, PrivateIpAddress, OsType, PublicIPAddress, Subscription, Cores, Memory, CreatedDate
$vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id
foreach($publicIp in $publicIps) {
if($nic.IpConfigurations.id -eq $publicIp.ipconfiguration.Id) {
$info.PublicIPAddress = $publicIp.ipaddress
}
}
[string]$sku = $vm.StorageProfile.ImageReference.Sku
[string]$os = $vm.StorageProfile.ImageReference.Offer
$osDiskName = $vm.StorageProfile.OsDisk.Name
$info.VMName = $vm.Name
$info.OsType = $os " " $sku
$info.ResourceGroupName = $vm.ResourceGroupName
$info.Region = $vm.Location
$vmLocation = $vm.location
$info.VmSize = $vm.HardwareProfile.VmSize
$info.VirtualNetwork = $nic.IpConfigurations.subnet.Id.Split("/")[-3]
$info.PrivateIpAddress = $nic.IpConfigurations.PrivateIpAddress
$info.Subscription = $subName
if ($vmLocation)
{
$sizeDetails = Get-AzVMSize -Location $vmLocation | Where-Object {$_.Name -eq $vm.HardwareProfile.VmSize}
}
$info.Cores = $sizeDetails.NumberOfCores
$info.Memory = $sizeDetails.MemoryInMB
$osDisk = Get-AzDisk -ResourceGroupName $vm.ResourceGroupName -DiskName $osDiskName
$info.CreatedDate = $osDisk.TimeCreated
$report =$info
}
}
$csv = $report | Select-Object VmName, ResourceGroupName, Region, VmSize, VirtualNetwork, PrivateIpAddress, OsType, PublicIPAddress, Subscription, Cores, Memory, CreatedDate
$csv | Export-Csv C:\temp\Inventory.csv -NoTypeInformation