Featured image of post Mini-blog: Wait for VM to come online, then execute Powershell direct

Mini-blog: Wait for VM to come online, then execute Powershell direct

During my labbing I’ve noticed I often need to wait for the VM to get online before executing some script or commands, to do that I use the following script:

First we get the VM Name, and enter the credentials for that specific VM:

1
2
3
4

$VMName = read-host "Please enter the VM-Name"
$VM = get-vm $VMName
$cred = Get-Credential -Message "Please enter credentials for the VM"

By getting the VM status we can use the VM.Heartbeat to check the actual status. We’re currently counting on the VM to be an unmonitored VM so the result we expect is “OkApplicationsUnknown” – This means the OS is up but the hypervisor has no idea if the VM applications are “healthy”.

To wait for the VM to get online we use a while loop to keep checking the heartbeat and if the status changes.

1
2
3
4
5

do
{
$VM = get-vm $VMName
} while ($vm.Heartbeat -ne "OkApplicationsUnknown")

Directly after the loop we are sure the VM is online, so we can execute our script via PowerShell Direct, here I simply print the hostname. 🙂

1
2

invoke-command -vmname $vmname -Credential $cred -ScriptBlock {write-host "My name is $env:COMPUTERNAME"}

Happy scripting!

All blogs are posted under AGPL3.0 unless stated otherwise
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy