VMware vSphere

 View Only

 Powershell / PowerCLI script

ian g's profile image
ian g posted Feb 03, 2025 09:20 AM

Hi,

I'm not so proficient in building the Powershell/PowerCLI scripts. I would like to create one that:

- Imports PowerCli module
- Connects to the vCenter
- Lists each hard disk for each VM including disk name (C, D, E, etc), disk capacity and free space
- Then exports the formatted table in CSV where each virtual machine's data is in a single line and disks details are in separate columns

I've been trying to find a good way to do so but I failed. Can anyone help with a good solution?

dabrigo's profile image
dabrigo

Hi Ian,

for that purpose you can use the free RVTools utility (https://www.robware.net/), you will find a tab with exactly the info you need ready to be exported in either CSV or XLS, along with many other data.

Reza Ardaneh's profile image
Reza Ardaneh

# Ensure you're connected to vCenter
Connect-VIServer -Server "your_vcenter_server"

# Create an array to hold disk info
$diskReport = @()

# Get all VMs
$vms = Get-VM

# Iterate through each VM
foreach ($vm in $vms) {
    Write-Host "VM: $($vm.Name)"
    
    # Get hard disks attached to the VM
    $hardDisks = Get-HardDisk -VM $vm
    
    foreach ($disk in $hardDisks) {
        # Get disk drive letter and free space
        $diskDrive = Get-VMGuestDisk -VM $vm | Where-Object { $_.MountPoint -eq $disk.Name }
        
        # Disk details
        $diskName = $diskDrive.MountPoint
        $diskCapacity = [math]::round($disk.CapacityKB / 1MB, 2) # Capacity in MB
        $diskFreeSpace = [math]::round($diskDrive.FreeSpaceMB, 2) # Free space in MB
        
        # Create an object for each disk and add to the array
        $diskReport += [PSCustomObject]@{
            VMName        = $vm.Name
            DiskName      = $diskName
            DiskCapacity  = $diskCapacity
            DiskFreeSpace = $diskFreeSpace
        }

        Write-Host "  Disk Name: $diskName"
        Write-Host "    Capacity (MB): $diskCapacity"
        Write-Host "    Free Space (MB): $diskFreeSpace"
    }
    Write-Host ""
}

# Export the report to a CSV file
$csvPath = "C:\path_to_save\VM_Disk_Report.csv"
$diskReport | Export-Csv -Path $csvPath -NoTypeInformation

# Confirm export
Write-Host "Disk report exported to: $csvPath"

# Disconnect from vCenter
Disconnect-VIServer -Server "your_vcenter_server" -Confirm:$false