To export the azure VMs using PowerShell, we first need to get their desired properties. The cmdlet Get-AZVM will get all the VMs connected to the particular subscription. To export them to the CSV file we can use the below command.
Get-AzVM | Export-Csv .\AZVMs.csv -NoTypeInformation
Once you run the above command, you will notice that you get all the properties of the VM, and sometimes they are not needed. To get the particular properties of the VM use the Select-Object (alias Select) command.
Get-AzVM | Select Name, ResourceGroupName, Location, @{N='VMSize';E={$_.HardwareProfile.VmSize}} | Export-Csv .\AzureVms.csv -NoTypeInformation
If you want to export the VMs from a particular Resource group,
Get-AZVM -ResourceGroupName TestRG | Export-CSV .\TestRGVMs.csv -NoTypeInformation
When you add -Status Parameter in the Get-AzVM command, it shows the power state of the virtual machine.
Get-AzVM -Status | Export-Csv .\AZVMs.csv -NoTypeInformation
If you need VMs from another subscription, you can use Set-AZContext or Select-AZSubscription command to switch the subscription and then use any of the above commands to get the VM details in the CSV file.