Hi Mounir,
Welcome to the Microsoft Q&A Platform! Thank you for asking your question here.
To retrieve free/used disk space on all your Azure VMs, you can use PowerShell and Azure's Invoke-AzVMRunCommand. This script allows you to execute commands remotely on Azure VMs and collect the required disk space data. Below are detailed steps:
Steps to Get Free/Used Disk Space for All VMs
Enable WinRM on the VM
Before running the PowerShell script, ensure that Windows Remote Management (WinRM) is enabled on your VMs. Open PowerShell on each VM and run:
Enable-PSRemoting -Force
This command configures the VM to accept remote PowerShell commands.
Install the Azure PowerShell Module (if not already installed):
Install-Module -Name Az -AllowClobber -Scope CurrentUser
Script to Retrieve Disk Space
The following script iterates through all VMs in a specified resource group, executes a command to check disk space on the C: drive, and outputs the results.
# Define the resource group and target VMs
$ResourceGroupName = "<YourResourceGroupName>" # Replace with your resource group name
$Command = @'
Get-PSDrive -Name C | Select-Object @{Name="Used (GB)";Expression={"{0:N2}" -f ($_.Used / 1GB)}},
@{Name="Free (GB)";Expression={"{0:N2}" -f ($_.Free / 1GB)}},
@{Name="Total (GB)";Expression={"{0:N2}" -f (($_.Used + $_.Free) / 1GB)}},
@{Name="Used Percentage";Expression={"{0:N2}" -f ($_.Used / ($_.Used + $_.Free) * 100)}}
'@
# Get all VMs in the resource group
$VMs = Get-AzVM -ResourceGroupName $ResourceGroupName
foreach ($VM in $VMs) {
$VMName = $VM.Name
$Result = Invoke-AzVMRunCommand -ResourceGroupName $ResourceGroupName -VMName $VMName -CommandId 'RunPowerShellScript' -ScriptString $Command
Write-Output "Results for VM: $VMName"
Write-Output $Result.Value
}
The script will display the following details for the C: drive of each VM:
Used Space (GB), Free Space (GB), Total Space (GB), Used Percentage
If an answer has been helpful, please consider accept the answer and "Upvote" to help increase visibility of this question for other members of the Microsoft Q&A community.