← script library

Automate Hyper-V Virtual Machine Creation with PowerShell

Hyper-VDecember 24, 2024

In this post, we will share a useful PowerShell script that automates the creation of virtual machines in Hyper-V. This script can be an invaluable tool for IT professionals looking to streamline their server provisioning process. With just a few parameters, you can easily spin up new virtual machines and save valuable time in your workflow. Before you begin, ensure that you have the Hyper-V role installed on your server and that you are running PowerShell with administrative privileges. Here is the PowerShell script that you can use:

powershell
# Define parameters for the new virtual machine
$vmName = "NewVM"
$vmMemory = 2048MB
$vmDiskSize = 20GB
$vmPath = "C:\HyperV\Virtual Machines\$vmName"
# Create a new virtual machine
New-VM -Name $vmName -MemoryStartupBytes $vmMemory -BootDevice VHD -Path $vmPath
# Set the virtual hard disk
New-VHD -Path "$vmPath\$vmName.vhdx" -SizeBytes $vmDiskSize -Dynamic
# Attach the virtual hard disk to the virtual machine
Add-VMHardDiskDrive -VMName $vmName -Path "$vmPath\$vmName.vhdx"
# Optional: Start the virtual machine
Start-VM -Name $vmName
Write-Host "Virtual machine '$vmName' created successfully."

Run it across your fleet

This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.

Ready when you are.

Try ServerEngine free for 7 days.