Tag Archives: get-vm

PS: One-line create a custom object list

The one-liner challenge for me today:

  • Get a list of random VMs from each ESXi host in a cluster
  • Send the host name, vm name and IP address to a CSV file

Normally, this is straight forward, but because we only need grab 2 VMs from each host, it is not possible to just  pipe the VM objects into a CSV file since the loop breaks between each host. The solution is to store all records into a array of custom objects and then pipe that into a CSV file at the end.

$ListOfVMs = @() ;
get-cluster | ? { $ -match "cluster1" } |
get-vmhost | % { $_ | get-vm | ? { $ -match "dev" } |
select -first 2 |
% { $t = @{} |
    select VMhost,Name,IPAddress ;
    $t.VMHost = $_.VMHost;
    $t.Name = $_.Name ;
    $t.IPAddress = $_.guest.IPAddress[0] ;
    $ListOfVMs += $t }
} ; $ListOfVMs | export-csv .\mylist.csv -NoTypeInformation


Leave a comment

Posted by on April 18, 2018 in powershell


Tags: , , ,

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: , , ,