Update : updated script to support Azure Az powershell module.
A good Governance and cost-management process is very important for any Cloud administrator. Microsoft provides excellent documentation on how these should be set up on cloud. Refer here for more details.
Here is a Powershell script to generate a report of Azure Virtual Machine power state in an Azure subscription. This script generates a csv file report with information if the VM is running or in deallocated state. It also reports the time when VM was shut down if it is in deallocated state.
I run this report to get an understanding if there is any VM which is still hanging there even after deallocated for so long. All these go to our cost saving initiatives to present some data towards Azure waste.
Before start using this script, make sure you have Azure Az Module installed and imported on the system. For more information on how to install and configure Az module refer following article : https://docs.microsoft.com/en-us/powershell/azure/new-azureps-module-az?view=azps-5.5.0
Let me know if this is helpful!
If you want to convert premium disks to standard disk in Azure to reduce unwanted cost of running non-critical VMs refer my post here.
$currentDir = $(Get-Location).Path
$oFile = "$($currentDir)\AzureVMPowerState.csv"
if(Test-Path $oFile){Remove-Item $oFile -Force}
"CurrentTime,ResourceGroupName,VMName,OSType,VMSku,VMStatus,PoweredOffTime" | Out-File $oFile -Append -Encoding ASCII
Get-AzResourceGroup | ForEach-Object{
$rgName = ""
$rgName = $_.ResourceGroupName
Get-AzVM -ResourceGroupName $rgName | ForEach-Object{
$vmName = $osType = $vmSku = $vmDetails = $vmStatus = $currentTime = ""
$vmStatusDetail = "Powered On"
$vmName = $_.Name
$osType = $_.StorageProfile.OsDisk.OsType
$vmSku = $_.HardwareProfile.VmSize
$vmDetails = Get-AzVM -ResourceGroupName $rgName -Name $vmName -Status
$currentTime = (Get-Date).ToString("HH:mm:ss")
foreach ($vmStatus in $vmDetails.Statuses)
{
$powerOffTime = ""
if($vmStatus.Code.CompareTo("PowerState/deallocated") -eq 0)
{
$powerOffTime = $vmDetails.Statuses[0].Time.ToString("MM-dd-yyyy")
$vmStatusDetail = $vmStatus.DisplayStatus
}
}
"$currentTime,$rgName,$vmName,$osType,$vmSku,$VMStatusDetail,$powerOffTime" | Out-File $oFile -Append -Encoding ASCII
}
}
Download above script and save it with a .ps1 file extension. Open powershell console and, login to your Azure account using – Login-AzAccount. It will prompt you to enter your Azure credentials.
After you login to Azure, run the powershell script saved in previous step.