This article is more than 1 year old
Want to deploy virtual machines in a hurry? PowerShell is your friend
Improve your automation
Step 2: Deploying our golden image
The next stage is to create virtual disks for the new server(s). You could create a differencing disk based on the golden image but I prefer to copy the entire virtual disk to create a standalone disk for the new virtual machine using the PowerShell Copy-Item cmdlet.
Copy-Item -Path "E:\VMs\GoldenImages\$($OriginatingVMName).VHDX" -Destination "E:\VMs\$($NewComputerName)_Disk.vhdx" | Out-Null
You can either set the destination parameter to point to a local folder or a universal naming convention path.
Once the VHDX has finished copying we then create a new virtual machine in Hyper-V using the New-VM cmdlet.
New-VM -Name $NewComputerName -VHDPath "E:\VMs\$($NewComputerName)_Disk.vhdx" -SwitchName $vSwitchName | Out-Null
The command above creates a virtual machine, attaches our freshly copied virtual disk and assigns the virtual machine a virtual switch to use. Once this has been done we can assign RAM and processor values.
p>Set-VMMemory -VMName Server1 -DynamicMemoryEnabled $True -StartupBytes 2GB -MinimumBytes 2GB -MaximumBytes 4GB Set-VMProcessor -VMName Server1 -Count 2 -Reserve 0 -Maximum 100 -RelativeWeight 100
Now that we have all of our individual steps scripted, let’s put them together and add some parameters so we don’t need to edit the script every time we want to deploy a new virtual machine.
Our completed script will look something like this:
Param( [Parameter(Mandatory=$true)][String]$NewComputerName, [Parameter(Mandatory=$true)][String]$OriginatingVMName, [Parameter(Mandatory=$true)][String]$vSwitchName #Add additional params such as memory settings )
Write-Verbose "Creating and configuring VM $NewComputerName" Copy-Item -Path "E:\VMs\GoldenImages\$($OriginatingVMName).VHDX" Destination "E:\VMs\$($NewComputerName)_Disk.vhdx" | Out-Null
New-VM -Name $NewComputerName -VHDPath "E:\VMs\$ $NewComputerName)_Disk.vhdx" -SwitchName $vSwitchName | Out-Null
Set-VMMemory -VMName Server1 -DynamicMemoryEnabled $True -StartupBytes 2GB -MinimumBytes 2GB -MaximumBytes 4GB
Set-VMProcessor -VMName Server1 -Count 2 -Reserve 0 -Maximum 100 -RelativeWeight 100 Write-Verbose "Complete"
Now we just need to start the virtual machine.