Jere's Techblog

Hyper-V Create Machine

I’d like to share a mini Script to create VirtualMachines with Hyper-V and Powershell. It is certainly not enterprise diveable. But it’s enough to create a VM for testing.

#by JKU 02.08.2019

#VM Base Information
$VMName = "TestVM2"
$DataPath = "C:\temp"
$DataVMPath = $DataPath + "\" + $VMName
$DiskDataPath = $DataPath + "\" + $VMName + "\" + $VMName + ".vhdx"
$Memory = 2GB
$Disk = 12GB
$CPUCores = 4
$VMGeneration = 2   #Options are "1","2"   -> If you don't have any idea, please let this at Value 2

#Options
$MountIso = "true"
$StartVMaftreCreation = "true"
$IsoPath = "C:\Cloud_JK\NextCloud\jere@nx2309.your-next.cloud\OS\win10\SW_DVD5_Win_Pro_10_64BIT_German_MLF_X20-25597.ISO"




#Script
IF(Get-VM -Name $VMName -ErrorAction SilentlyContinue){
    Write-Warning "$VMName : Machine already exists! Please verify your Values."
    return
}
IF(Test-Path $DataVMPath){
    Write-Warning "$DataVMPath : Folder already exists! Please verify your Values."
    return
}

Write-Host "Start to create VM $VMName" -foregroudcolor yellow
New-VM -Name $VMName -path $DataPath -MemoryStartupBytes $Memory -NewVHDSizeBytes $Disk -NewVHDPath $DiskDataPath -Generation $VMGeneration

$Vm = (Get-VM -Name $VMName)
Set-VM -VM $Vm -ProcessorCount $CPUCores


IF($MountIso -eq "true"){
    $DVD = Add-VMDvdDrive -VMName ($Vm).Name -Path $ISOPath -Passthru
    Set-VMFirmware -VM $VM -FirstBootDevice $DVD
}
IF($StartVMaftreCreation -eq "true"){
    Start-VM -Name $VMName
}

Write-Host "Script End"

Below are two links to similar topics.

To create a virtual machine from a specific template (Hyper V)

Continue reading...