I'm trying to power on VMs which I previously powered off using PowerCLI.
When I try to run the following script (part of a bigger one) I still get a status which is not "PoweredOn", even though I can see on the VSphere console that the machine was powered on.
I get this also in other situations and I try to re-get the virtual machines, but I fail to make this work.
If I don't re-get the VMs, I sometimes get error claiming the VM I'm referring to is null.
What am I doing wrong? What am I missing?
Here are the script lines:
$VMs = get-vm | Where-object {($_.Name -like $vmNamePatternToSearch)}# | Out-Null
foreach ($vm in $VMs) {
#$vm = Get-VM -Name $vm.Name #| Out-Null
if ($vm.powerstate -ieq "poweredoff") {
Start-VM -VM $vm -Confirm:$False | Out-Null
Write-Host -NoNewline 'Powering On' $vm.Name.ToString().PadRight(22)
do {
Start-Sleep -Seconds 1
Write-Host -NoNewline '|' $vm.powerstate
} until ($vm.powerstate -ieq "PoweredOn")
Write-Host
}
}
So my output is "| PoweredOff| PoweredOff| PoweredOff| PoweredOff| PoweredOff|..."
Even though the machine is already up.
Even if I un-comment the "#$vm = Get-VM -Name $vm.Name #| Out-Null" line - still no go.
I would appreciate your input.
Thanks!
PowerShell's objects are point in time references. So your vm
variable will continue to reflect the status of the VM at the time you ran the get-vm
cmdlet.
To help overcome this you could run something like the following to reference the updated state of the VM during your loop:
do {
Start-Sleep -Seconds 1
Write-Host -NoNewline '|' $vm.powerstate
} until ((Get-VM $vm).powerstate -ieq "PoweredOn")