Creating Virtual machines #1: Creating the VM

I’ve had two projects in mind for a while.  First I need to build a new WSUS server in my virtual environment & secondly I want to automate as much of the VM creation and configuration as possible. Oh – and I’m not using SC Virtual Machine Manager. 

I’ll be using the Hyper-V cmdlets that come with Windows 2012.

I covered some of this in PowerShell and WMI but that was for Windows 2008 R2 and I was using James O’Neills hyper-v functions. 

Does it get any easier with the cmdlets

This is what I came up with

function new-virtualmachine {            
[CmdletBinding()]            
param (            
 [parameter(Mandatory=$true)]            
 [string]$name,            
             
 [parameter(Mandatory=$true)]            
 [string]$path,            
 [Int64]$mem = 4GB,            
 [string]$vswitch = "Local Area Connection - Virtual Network",            
            
 [ValidateSet("Windows2012", "Windows2008R2", "Windows7")]            
 [string]$iso,            
            
 [switch]$startvm            
)            
            
Write-Verbose -Message "Testing VM Path"            
$vpath = Join-Path -Path $path -ChildPath $name            
if (-not (Test-Path -Path $vpath)){            
 New-Item -Path $path -Name $name -ItemType Directory            
}            
            
switch ($iso){            
 "Windows2012" {$isopath = "C:\Source\Windows 2012 RTM\en_windows_server_2012_x64_dvd_915478.iso"}            
 "Windows2008R2" {$isopath = "C:\Source\Window 2008R2\en_windows_server_2008_r2_standard_enterprise_datacenter_and_web_with_sp1_x64_dvd_617601.iso" }            
 "Windows7" {$isopath = "C:\Source\Windows7 RTM\en_windows_7_ultimate_x86_dvd_x15-65921.iso"}            
}            
            
New-VM -Name $name -MemoryStartupBytes $mem -Path $vpath -BootDevice CD -NewVHDPath "$vpath\$name.vhdx" -NewVHDSizeBytes 120GB -SwitchName $vswitch            
Add-VMDvdDrive -VMName $name -Path $isopath            
            
if ($startvm){Start-VM -Name $name}            
}


The new VM name and path are mandatory, I’ve set a default memory size of 4GB  and added a default Virtual switch. I’m adding the iso file containing the OS I want to install – that’s constrained by the set validation and I have a final parameter that allows me to start the VM.



if the path in which I want to create the VM doesn’t exist I create it.



A switch statement is used to set the full path to the iso file.



The New-VM cmdlet is used to create the VM based on the information provided.  I do hard code the fact that I’m setting the VM to boot from the CD and that the virtual disk will be 120GB



Add-VMDvdDrive is used to add the DVD drive to the VM (the controller location is automatically worked out) and the iso file mounted.



If the startvm switch is used then the VM starts and OS install commences. I’m deliberately NOT automating the OS setup at this time – that may be another project.

Leave a Reply