I am deploying Windows VMs with PowerShell Direct and Hyper-V. The VM has to be restarted several times, and as soon as Windows starts again, the script should resume and run other commands. For example, here is a part of my current script:
Invoke-Command -VMName 'server2.example.com' -Credential $credential -ScriptBlock {
Rename-Computer -NewName 'server2' -Force -Restart
}
Start-Sleep -s 10
Right now, I use Start-Sleep -s 10
to make sure that the machine starts before it resumes running other commands. However, I think that this part is incorrect. Do I maybe need to run Restart-VM VMNAME
on my machine instead of using the -Restart
argument in Rename-Computer -NewName 'svn2' -Force -Restart
in the VM? Or is there a better approach?
My problem is that the script continues running the commands when the machine is still restarting. Therefore, I am receiving errors. This is what I want to solve.
It appears that the correct solution here is to restart the VM from the host computer using Restart-VM
with the -Wait
parameter.
So I had to replace this
Rename-Computer -NewName 'server2' -Force -Restart
}
Start-Sleep -s 10
with this
Rename-Computer -NewName 'server2' -Force
}
Restart-VM $myVmName -Wait