Automation PowerShell Script to Create Machine in Hyper-V - Knowledgebase - CLOUDRAIN IT SOLUTIONS

Automation PowerShell Script to Create Machine in Hyper-V Print

  • 0

Automation PowerShell Script to Create Machine in Hyper-V

 

# Detect switch automatically
$Switch = Get-VMSwitch | Where-Object {$_.SwitchType -eq "External"} | Select-Object -First 1

if (!$Switch) {
$Switch = Get-VMSwitch | Select-Object -First 1
}

$SwitchName = $Switch.Name

Write-Host "Using Virtual Switch:" $SwitchName -ForegroundColor Cyan

# Ask user input
$VMPath = Read-Host "Enter VM Storage Path (Example: F:\VM)"
$VMName = Read-Host "Enter VM Name"
$VHDSizeGB = [int64](Read-Host "Enter VHD Size (GB)")
$MemoryGB = [int64](Read-Host "Enter Memory (GB)")
$CPUCount = [int](Read-Host "Enter Number of Processors")
$MACAddress = Read-Host "Enter MAC Address (Example: 00155D123456)"
$ISOPath = Read-Host "Enter ISO Path (Leave blank if none)"

# Validate MAC
if ($MACAddress -notmatch "^[0-9A-Fa-f]{12}$") {
Write-Host "Invalid MAC Address format" -ForegroundColor Red
exit
}

# Paths
$VMFolder = "$VMPath\$VMName"
$VHDPath = "$VMFolder\$VMName.vhdx"

# Create folder
New-Item -ItemType Directory -Path $VMFolder -Force | Out-Null

# Create disk
New-VHD -Path $VHDPath -SizeBytes ($VHDSizeGB * 1GB) -Dynamic

# Create VM
New-VM `
-Name $VMName `
-MemoryStartupBytes ($MemoryGB * 1GB) `
-Generation 2 `
-VHDPath $VHDPath `
-Path $VMFolder `
-SwitchName $SwitchName

# Configure CPU
Set-VMProcessor -VMName $VMName -Count $CPUCount

# Configure MAC
Set-VMNetworkAdapter -VMName $VMName -StaticMacAddress $MACAddress

# Attach ISO if valid
if ($ISOPath -ne "" -and (Test-Path $ISOPath)) {
Add-VMDvdDrive -VMName $VMName -Path $ISOPath
}

# Start VM
Start-VM $VMName

Write-Host ""
Write-Host "VM Successfully Created!" -ForegroundColor Green
Write-Host "VM Name : $VMName"
Write-Host "Switch : $SwitchName"
Write-Host "Location: $VMFolder"


Was this answer helpful?

« Back

Powered by WHMCompleteSolution