This month’s T-SQL Tuesday is hosted by Rob Sewell (b|t) and surprise, surprise, it focuses on Powershell so I thought I’d write a quick post on how I’ve streamlined a pretty much weekly task that I perform, creating VMs.
I’m constantly spinning up VMs and then blowing them away. Ok, using the Hyper-V GUI isn’t too bad but when I’m creating multiple machines it can be a bit of a pain.
So here’s the details on the script I’ve written, hopefully it could be of some use to you too.
First check that your machine has the Hyper-V powershell module installed: –
Get-Module
If it’s not installed, you can either enable through the GUI: –
Or via script: –
Install-WindowsFeature -Name Hyper-V-PowerShell
N.B. – You won’t need to do this if, like me, you’re working with Hyper-V Server 2012 R2
Then you’re good to go creating VMs! All you need is the ISO for the OS that you want the machine to run.
Here’s the code: –
$BootDevice = Read-Host -Prompt "Set VM boot device" $ServerName = Read-Host -Prompt "Enter VM Name" $VMGeneration = Read-Host -Prompt "Enter VM Generation" [int]$VMMemoryGB= Read-Host -Prompt "Set VM Memory (GB)" $VMCPU = Read-Host -Prompt "Set Number of CPUs" $NetworkAdapter = Read-Host -Prompt "Set Network Adapter" $VHDPath = Read-Host -Prompt "Set VHD Path" [int]$VHDSizeGB = Read-Host -Prompt "Set VHD Size (GB)" $SecureBoot = Read-Host -Prompt "Secure Boot On/Off" $ISOPath = Read-Host -Prompt "Set ISO Path" $VMMemory = ((($VMMemoryGB*1024)*1024)*1024) $VHDSize = ((($VHDSizeGB*1024)*1024)*1024) New-VM -BootDevice $BootDevice -Name $ServerName -Generation $VMGeneration -MemoryStartupBytes $VMMemory -SwitchName $NetworkAdapter -NewVHDPath $VHDPath -NewVHDSizeBytes $VHDSize Set-VMProcessor $ServerName -Count $VMCPU Set-VMFirmware -VMName $ServerName -EnableSecureBoot $SecureBoot Set-VMDvdDrive -VMName $ServerName -Path $ISOPath
Either copy the script here or download it from my GitHub.
Now, I’ve got this saved on my Hyper-V host as CreateNewVM.ps1 and I execute it through a remote powershell session. Here it is in action: –
Thanks for reading!