Scripts: Export VM Name and VMDK Size 1 minute read
Here is a script that I use to gather some size data and spit out a spreadsheet listing name and VMDK size.# PowerCLI Script to gather VM Information (Name, VMDK Size)
# Scripted by James Bowling <jbowling@vsential.com>
#
#Global Functions
function Get-VmSize( $vm )
{
#Initialize variables
$VmDirs = @()
$VmSize = 0
$searchSpec = New-Object VMware.Vim.HostDatastoreBrowserSearchSpec
$searchSpec .details = New-Object VMware.Vim.FileQueryFlags
$searchSpec .details.fileSize = $TRUE
Get-View -VIObject $vm | % {
#Create an array with the vm's directories
$VmDirs += $_ .Config.Files.VmPathName.split( "/" )[ 0]
$VmDirs += $_ .Config.Files.SnapshotDirectory.split( "/" )[ 0]
$VmDirs += $_ .Config.Files.SuspendDirectory.split( "/" )[ 0]
$VmDirs += $_ .Config.Files.LogDirectory.split( "/" )[ 0]
#Add directories of the vm's virtual disk files
foreach ( $disk in $_ .Layout.Disk) {
foreach ( $diskfile in $disk .diskfile){
$VmDirs += $diskfile .split( "/" )[ 0]
}
}
#Only take unique array items
$VmDirs = $VmDirs | Sort | Get-Unique
foreach ( $dir in $VmDirs ){
$ds = Get-Datastore ( $dir .split( "[" )[ 1]) .split( "]" )[ 0]
$dsb = Get-View (( $ds | get-view) .Browser)
$taskMoRef = $dsb .SearchDatastoreSubFolders_Task( $dir ,$searchSpec )
$task = Get-View $taskMoRef
while ( $task .Info.State -eq "running" -or $task .Info.State -eq "queued" ){ $task = Get-View $taskMoRef }
foreach ( $result in $task .Info.Result){
foreach ( $file in $result .File){
$VmSize += $file .FileSize
}
}
}
}
return $VmSize
}
# Variables
$VIServer = "VISERVER"
$username = "changeme"
$password = "supersecure"
$Folder = "C:"
# Connect to VIServer
Connect-VIServer $VIServer -user $username -Password $password
#Initialise Array
$Report = @()
# Gather VM Information
$AllVMs = Get-View -ViewType VirtualMachine | Where { -not $_ .Config.Template}
$SortedVMs = $AllVMs | Select * , @{ N = "NumDisks" ;E ={ @( $_ .Guest.Disk.Length)}} | Sort-Object -Descending NumDisks
ForEach ( $VM in $SortedVMs ){
$Details = New-object PSObject
$Details | Add-Member -Name Name -Value $VM .name -Membertype NoteProperty
$DiskNum = 0
Foreach ( $disk in $VM .Guest.Disk){
$Details | Add-Member -Name "Disk $( $DiskNum ) Capacity(GB)" -MemberType NoteProperty -Value ([ math]::Round( $disk .Capacity/ 1024MB))
$DiskNum ++
}
$Report += $Details
}
$Report | Export-Csv "C:VMDiskSize.csv"
# Disconnect from VIServer
Disconnect-VIServer $VIServer -Confirm:$False
Leave a Comment