Go to ...

RSS Feed

March 29, 2020

Hyper-V – Create shortcut for virtual machine


It’s easy and convenient to start and stop a Hyper-V virtual machine from a PowerShell script. Only three command lines are required: start the VM, launch Virtual Machine Connection window, and when the VM Connection is closed, shut down the VM. It is one of the shortest PS scripts I use. Thus, for example, the following script would run a virtual machine named W10 PRO 1909 EN-GB:

Start-VM "W10 PRO 1909 EN-GB"
C:\Windows\System32\vmconnect.exe localhost "W10 PRO 1909 EN-GB" | Out-Null
Stop-VM "W10 PRO 1909 EN-GB"

Notice that on the second line, the command is piped to the NULL device. What this does is wait until the VM Connection window is closed. Only then does the script advance to the last line, in which it shuts down the VM. Practical. Replace the VM name in all three lines, save the script as AnyName.ps1. You can now start the named VM simply by right clicking the script and selecting Run with PowerShell:

Click screenshots to open them in new tab.

When the script is run, a PowerShell window is opened, to show progress:

When the VM starts fully, the VM Connection window opens. When the user then closes that VM Connection window, the VM will be shut down. Here again, PS shows progress:

What if the user wants to hide the PowerShell window? For that, we need a simple VB Script:

command = "powershell.exe -nologo -command G:\Hyper-V\ShortcutDemo\W10 PRO 1909 EN-GB.ps1"
set shell = CreateObject("WScript.Shell")
shell.Run command,0

Replace the path in the first line with your actual path. In my case, the PS script to start the VM named W10 PRO 1909 EN-GB resides on my G: drive, in folder Hyper-V\ShortcutDemo. Save the script as AnyName.vbs. When run, it hides the PowerShell window, starting the VM named in the PS script in the background, opens a VM Connection window when the VM starts, and shuts down the VM when the user closes the VM Connection window. This is perhaps more elegant, because the small cosmetic nuisance — the PS window shown as long as the VM is running — is taken care of invisibly in the background.

One more step: create a shortcut for your VB script. When that’s done, change the icon for the shortcut if the default VBS icon does not please you. In the next screenshot, the two required scripts, one PS and one VBS, and the final shortcut to run my VM all appear:

It really is practical to have shortcuts for all your virtual machines on the desktop!

Kari

 

 

Author: Kari Finn

A former Windows Insider MVP, Kari started in computing in the mid 80’s writing code for VAX / VMS systems. Since then, he’s worked in a variety of IT positions. He specializes in Windows image capture, customization, repair and deployment as well as Hyper-V virtualization. Kari is a proud Team Member at number #1 Windows site TenForums.com.

Leave a Reply

More Stories From Hyper-V