About…

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:

$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.

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. 🙂

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

Happy scripting!

Leave a Comment

(0 Comments)

Your email address will not be published. Required fields are marked *