Automate Hyper-V Virtual Machine Creation with PowerShell

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:

# 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."