Spin Up Virtual Machines with PowerShell
This blog post will walk you through a PowerShell script that allows you to spin up virtual machines using the Hyper-V platform. The script is designed to make it easy to create new VMs and configure them for installation.
Prerequisites
The Script
The script begins by clearing the host and prompting the user to enter the number of virtual machines they want to create. It then enters a loop that continues until the specified number of VMs has been created.
Clear-Host
$vmno = read-host "Enter no of vm's needed"
$i = 0
do {
$vmname = read-host "Enter New VM Name, or ! to quit."
if ($null -ne $vmname -and $vmname -ne "!") {
# Check if the VM already exists
$path = ".\VMs\$vmname.vhdx"
if (!(test-path $path)) {
# Create a new VM
$vmgen = read-host "VM Generation, e.g. 1 or 2"
Hyper-V\New-VM -NewVHDPath $path -NewVHDSizeBytes 40gb -Name $vmname -Generation $vmgen -MemoryStartupBytes 4gb -Path .\vmdata -SwitchName "virtual switch"
# Add an ISO drive to the VM
$isos = Get-ChildItem -Path "c:\iso\" -Filter "*.iso" | Select-Object -expandproperty PSchildname
Write-host "Please Select OS "
$s = 0
foreach ($iso in $isos) {
if ($s -eq 0) {
$OS = read-host "(Y/N) Do you want to install" $iso
if ($os -eq "y") {
Add-VMDvdDrive -vmName $vmname -Path "C:\iso\$iso"
Set-VMDvdDrive -VMName $vmname -Path "C:\iso\$iso"
$s = 1
}
}
}
# Configure the VM's firmware and start it up
$dvd = Get-VMDvdDrive -VMName $vmname
Set-VMFirmware -VMName $vmname -FirstBootDevice $dvd
Start-VM -Name $vmname
VMConnect.exe localhost $vmname
# Increment the counter
$i++
} else {
Write-host "$vmname already exists :(" -ForegroundColor Red
}
}
} until ($i -eq $vmno)
How It Works
Creating a New VM
The script uses the `New-VM` cmdlet to create a new virtual machine. You are prompted to enter the name of the VM and specify its generation (1 or 2). The script also asks you to select an ISO file from the directory containing your operating system install media.
Adding an ISO Drive
The script uses the `Add-VMDvdDrive` cmdlet to add a DVD drive to the VM. You are prompted to select which ISO file to use for installation.
Key Code Snippets
$vmno = read-host "Enter no of vm's needed"
$i = 0
do {
$vmname = read-host "Enter New VM Name, or ! to quit."
if ($null -ne $vmname -and $vmname -ne "!") {
# ... (rest of the script)
}
} until ($i -eq $vmno)
Usage Examples
This script is designed to be interactive, so you'll need to run it in an environment where you can respond to prompts. For example:
Conclusion
This script provides a convenient way to spin up virtual machines using PowerShell and Hyper-V. With this script, you can easily create new VMs and configure them for installation with your preferred operating system.