Tag Archives: get-vm

PowerCLI: Listing VMs from a bunch of vCenters

I need to grab all the VMs in a list of vCenters, but for each line of VM, I need to know which cluster and ESXi host they sit in. The original script was this;

Get-content .\vc.txt |
% {$vc=$_ ; connect-viserver $vc ; Get-VM |
Select Name, Vmhost, @{Name="Cluster";
Expression={ ((get-vmhost $_.vmhost).parent)}}, Folder,
@{Name="vCenter"; Expression= {$vc}} |
export-csv .\$vc.txt -NoTypeInformation ;
disconnect-viserver $vc –force –confirm:$false }

Even thought the code was straight forward with just a single get-VM execution, it was very slow. The reason was the Cluster field code block, which executes get-vmhost to get the cluster name for each VM, took time to execute.

@{Name="Cluster"; Expression={ ((get-vmhost $_.vmhost).parent)}}

A faster one-line calls each cluster first, then calls each VM in turn.

Get-content .\vc.txt |
% {$vc=$_ ; connect-viserver $vc ; Get-Cluster |
% { $clus=$; Get-VM -Location $Clus |
% { "$($`t$($`t$($_.folder)`t$($_.vmhost)`t$Clus`t$vc" |
out-file .\$vc.txt -append }} ;
disconnect-viserver $vc –force –confirm:$false }
Leave a comment

Posted by on May 19, 2017 in powershell, vmware


Tags: , , ,