My First (Useful) PowerShell Script!

Heard of PowerShell? No? Just Kidding! Even if you run your IT department under a rock or on Mars, you've heard of PowerShell - It's that ubiquitous!

I've always been interested in picking it up as a skill, it is an extremely useful skill to have, however, I've never had the time and when I've had the time, I've been lazy. The question always was when will I find the time? Well, as the old adage goes, there's no time like the present.

I was in the process of configuring my new work laptop, running Windows 8, with Client Hyper-V. I had all my Sysprep'ed VHD/VHDX files in a folder and was about to follow this process to create new virtual machines:

  1. Create a new differencing disk, with the parent disk being one of the sysprep'ed VHD/VHDX files (I have one for every version of Windows)
  2. Create a new virtual machine and point it to the VHD/VHDX create in the previous step.

These steps are all well and good if you only want to set up a couple of virtual machines. However, if you find yourself performing these steps over and over again, you'll come to hate that little 'Next' button on the New Hard Disk or New Virtual Machine wizards. Enter PowerShell.

I fired up the PowerShell ISE (Enable Admin Tools on the Start Screen - Settings - Tiles), built the commands using the Command Add-On (View Menu - Show Command Add-on) and voila! My first PowerShell Script!

$VMOS = $args[0]
$VMName = $args[1]
$DiskExtn = ".vhd"

if ($VMOS -eq "WIN2012") {$DiskExtn = ".vhdx"}
elseif($VMOS -eq "WIN8") {$DiskExtn = ".vhdx"}

$VHDParentPath = "C:\HyperV\BaseVHDs\" + $VMOS + $DiskExtn
$VHDPath = "C:\HyperV\VHDs\" + $VMName + $DiskExtn
$VMPath = "C:\HyperV\VMs\" + $VMName

New-VHD -ParentPath $VHDParentPath -Path $VHDPath
New-VM -VHDPath $VHDPath -MemoryStartupBytes 1073741824 -Name `
$VMName -Path $VMPath -SwitchName VM2VM

That's it. 15 minutes, a bit of Binging for PowerShell Syntax and I can now create a new virtual machine with any version of Windows, in a few keystrokes and 10 seconds.

Skip to main content