Streamline Hyper-V VM Creation: PowerShell Automation for Effortless Virtualization
If you are using Hyper-V for virtualization, You can create Hyper-V VMs using Hyper-V Manager GUI.However, creating 500 VMs or more manually is very difficult for clarity and conciseness.I am providing a script that allows you to automate the creation of VMs with just one click for better readability and flow..
Sample PowerShell Script for Automate VM
Requirements
Specs📝:
A new VM with 2 CPUs, 8GB RAM and 20GB storage.
Set up the Execution Policy
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Note Down the Switch
Get-VMSwitch * | Format-Table Name
Script
# Import the Hyper-V module
Import-Module Hyper-V
# Set base variables
$vmBaseName = "VM"
$vmCount = 10 #Set Howmany VM you want to Create Automatically
$vmMemory = 1GB
$vmVhdSize = 1GB
$vmPathBase = "C:\HyperV\VMs"
$vhdPathBase = "C:\HyperV\VHDs"
$virtualSwitch = "Intel(R) Ethernet Connection (5) I219-LM - Virtual Switch" ## Give the Switch Name which You Noted down
$vmGeneration = 1 # Set the VM generation to 1
# Create directories for VMs and VHDs if they don't exist
if (-Not (Test-Path $vmPathBase)) {
New-Item -Path $vmPathBase -ItemType Directory
}
if (-Not (Test-Path $vhdPathBase)) {
New-Item -Path $vhdPathBase -ItemType Directory
}
# Loop to create VMs
for ($i = 1; $i -le $vmCount; $i++) {
$vmName = "$vmBaseName$i"
$vmPath = "$vmPathBase\$vmName"
$vhdPath = "$vhdPathBase\$vmName.vhdx"
try {
# Create the VM without an OS
New-VM -Name $vmName -MemoryStartupBytes $vmMemory -Generation $vmGeneration -Switch $virtualSwitch -Path $vmPath
# Create a new VHD for the VM
New-VHD -Path $vhdPath -SizeBytes $vmVhdSize -Dynamic
# Attach the VHD to the VM
Add-VMHardDiskDrive -VMName $vmName -Path $vhdPath
# Enable all integration services for the VM
$integrationServices = Get-VMIntegrationService -VMName $vmName
foreach ($service in $integrationServices) {
Enable-VMIntegrationService -VMName $vmName -Name $service.Name
}
Write-Host "Successfully created VM: $vmName with integration services enabled"
}
catch {
Write-Host "Failed to create VM: $vmName. Error: $_"
}
}
Write-Host "Created $vmCount VMs successfully."
After that Save the above script in .ps1 extension.
Ex: createvm.ps1
After that go to the Directory and run the above script in windows powershell of VM executing by:- ./<filename>.ps1
Ex: ./createvm.ps1
Summery:
Creating VM manually is Lengthier task.So, if you are scaling the things you should automate your jobs to streamline the workflow.