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.