Automating Hyper-V Host VMs Startup / Shutdown | Quisitive
Automating Hyper-V Host VMs Startup / Shutdown
October 31, 2015
Quisitive
Read below

In today’s blog we’ll look at Automating Hyper-V Host VMs Startup / Shutdown.

Now, depending on your situation, you may want to shutdown all or certain VMs on your host for maintenance, updates, backups or just recover resources from non-production VMs.

You may also want to schedule times to ensure that only certain VMs are started back up.

To shutdown all VMs on a Hyper-V host, the script is very simple:

12345[cmdletbinding()]Param($vmhost = ‘<your host name>’)$runningVM = Get-VM -ComputerName $vmhost| where state -eq ‘running’foreach ($cn in $runningVM){Stop-VM $cn.name -asjob}

Simply save the above code as a .ps1 file and execute via PowerShell (or better yet, Task Scheduler) and any running VM will be shut down. The AsJob parameter means each task will run in the background silently. This can easily be adapted with the notes field mentioned below to shut down a subset of your VMs, such as all non-production VMs.

The result: All running VMs immediately begin shutting down.

image

For the startup scenario, it’s only slightly different. In my case, I almost never want every VM started up, but instead want only certain VMs like my gateway, domain controller and SQL to start back up automatically on a schedule. One simple way of doing that is to use the “Notes” field in the VM properties. In my case, I added the word “Prod” as a trigger word, but you can use anything here.

image

Once I’ve tagged all of my “Prod” VMs, I’m able to look that Notes field up in my startup script.

12345[cmdletbinding()]Param($vmhost = ‘<yourhostname>’)$VMtoStart = Get-VM -ComputerName $vmhost| where notes -contains ‘Prod’foreach ($cn in $VMtoStart){Start-VM $cn.name -asjob}

The Result: The desired VMs begin starting up.