Tuesday, October 16, 2012

Quick check on number of VMs powered on and off in multiple VCs

Recently there was a need to quickly report the number of VMs in all VCs, ideally with numbers for powered on and powered off VMs. We have multiple VCs (10 plus), not in linked mode, so it meant connecting to each and counting or exporting the information.

It’s fairly easy to get this information, but figured a script may be in order, in case the request was made again in the future, so this is what I came up with. It’s rough and ready, but did what I needed it to do. And yes, there are other scripts and tools (RVTools, PowerGUI with the VMware powerpack etc) that can do it, but this is partly an exercise in trying to get to grips with Powershell and PowerCLI.

It also spits out a couple of CSV files with a basic host report and VM report per VC in files named per VC. Assumes credentials are sorted in some way for conveniance - ie, credentials store.

The VCs to check are listed in the vclist.txt file

$currVC = Get-Content "vclist.txt"
foreach ($targetVC in $currVC) {
        Connect-VIServer $targetVC
        $hostCount = Get-VMhost
        write-host "Total number of hosts in $targetVC :" ($hostCount).count
 
# VM's, powered on and memory count
        Write-Host "Collecting VM information"
        $OutputFile = $targetVC + ".csv"
        $totalvms = get-vm | where{$_.powerstate -eq "PoweredOn" } |`
                select name, powerstate, numcpu, memorymb | `
                export-csv -NoTypeInformation $outputFile | out-null
 
 
        $pvms = Get-VM
        write-host "Powered on: " ($pvms | where {$_.PowerState -eq "PoweredOn"}
).Count
        write-host "Powered off: " ($pvms | where {$_.PowerState -eq "PoweredOff
"}).Count

# VMhost details
        Write-Host "Collecting host information"
        $HostOutputFile = $targetVC + "-vmhost.csv"
        $totalHosts = get-vmhost | select name, numcpu, CPUTotalMHz, MemoryTotal
MB, MemoryUsageMB, Parent |`
                Export-Csv -NoTypeInformation  $HostOutputFile | out-null
 
}
 
Disconnect-VIServer -Confirm:$false