Search code examples
powershellvmwarepowerclivcenter

PowerCLI: Work with VMs on multiple vCenter servers


I have a script that will power off and DeletePermanently all VMs that match a certain prefix. I use this when testing other automation tools to make it easy to reset the lab. The script connects to multiple, pre-defined vCenter servers and then gets a list of all the VMs. The problem I have is that when I try to power off or delete the VMs, it says "Could not find VirtualMachine with name 'VMNAME'."

Code that connects to the vCenter servers:

$vcservers = @("VC1","VC2")
Connect-VIServer $vcservers

Code that gets a list of VMs from both vCenter servers:

$prefix = "TEST"
ForEach ($vc in $vcservers) {
    $vms += Get-VM -Server $vc | where {$_.Name -like "$prefix*"}
}

Code that powers off and deletes each VM:

ForEach ($vm in $vms) {
    $vmname = $vm.name
    if ($vm.PowerState -eq "PoweredOn") {
        Stop-VM -VM $vmname -confirm:$false
        Remove-VM -VM $vmname -DeletePermanently -confirm:$false
    }
}

I have set the "Multiple" property on the Users and AllUsers scope by using Set-PowerCLIConfiguration, so it should search all vCenter servers, but for some reason it is not working.

EDIT 1/25/17 Updated the code to make the $vcservers variable consistent.


Solution

  • Since the first issue (related to variable naming) was resolved, I'm currently suspecting that the issue is due to PowerCLI being unsure on which VCenter the VMs you want to delete live. Thus, you could go VCenter by vCenter instead of trying to run against all vCenters at once:

    $prefix = "TEST"
    $vcservers = @("VC1","VC2")
    ForEach ($vc in $vcservers) {
        Connect-VIServer $vc
        $vms += Get-VM -Server $vc | where {$_.Name -like "$prefix*"}
    
        ForEach ($vm in $vms) {
            $vmname = $vm.name
            if ($vm.PowerState -eq "PoweredOn") {
                Stop-VM -VM $vmname -confirm:$false
                Remove-VM -VM $vmname -DeletePermanently -confirm:$false
            }
        Disconnect-VIServer $vc
    }