在日常工作中,经常遇到Hyper-V创建虚拟机的情况。
手动创建十分繁琐且缓慢,以下是通过PowerShell创建Hyper-V虚拟机的方式。
PowerShell自动创建虚拟机
Install_Ubuntu.ps1
# 检查是否以管理员身份运行,如果不是,则重新以管理员身份运行
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
# 重新以管理员身份运行脚本
Start-Process powershell.exe -ArgumentList " -NoProfile -ExecutionPolicy Bypass -File "$($MyInvocation.MyCommand.Path)"" -Verb RunAs
Exit
}
function Create-VM {
Param(
[Parameter(Mandatory=$true)]
[string]$VMName,
$VHDPath, # VHD template path, can be empty
$BootOp = "CD", # Boot Up
$VMRootPath = "F:\Hyper-V\", # VM Save Path
$VMGen = 1, # Memory Gen 1 or 2
$VMSwitch = "Default Switch", # Switch Name
$VMISOPath = "E:\系统盘\Ubuntu Server 22.04.3\ubuntu-22.04.3-live-server-amd64.iso", # ISO path, can be empty
$VMDiskSize = 50GB,
$VMMem = 4GB,
$VMProcessorCount = 2,
$StaticMemory = $false
)
if ($VMRootPath -match "\\$") {
$VMRootPath = $VMRootPath -replace "\\$"
}
# judge VM path --inexistence,Create
if (!(Test-Path -Path $VMRootPath)) {
New-Item $VMRootPath -ItemType Directory
}
$VMPath = (Get-Item $VMRootPath).FullName + "\" + $VMName
if (!(Test-Path $VMPath)) {
New-Item $VMPath -ItemType Directory
}
# Use existing template VHD or create a new one
if ($VHDPath) {
Get-Item $VHDPath
Copy-Item -Path $VHDPath -Destination $($VMPath + "\" + $VMName + ".vhdx")
New-VM -Name $VMName -MemoryStartupBytes 4GB -Path $VMPath -Generation 1 -SwitchName "Default Switch"
Add-VMHardDiskDrive -VMName $VMName -Path $($VMPath + "\" + $VMName + ".vhdx") -ControllerType IDE
$VMDiskDrive = Get-VMHardDiskDrive -VMName $VMName
Set-VMFirmware -FirstBootDevice $VMDiskDrive -VMName $VMName
} else {
$VMHDPath = $VMPath + "\" + $VMName + ".vhdx"
# Check if file exists and delete if it does
if (Test-Path $VMHDPath) {
Remove-Item $VMHDPath -Force
}
$VMHDPath = New-VHD -Path $VMHDPath -Dynamic -SizeBytes $VMDiskSize
New-VM -Name $VMName -MemoryStartupBytes $VMMem -Path $VMPath -Generation 1 -SwitchName "Default Switch" -BootDevice $BootOp
Add-VMHardDiskDrive -VMName $VMName -Path $VMHDPath.Path -ControllerType IDE
}
if ($VMISOPath) {
Set-VMDvdDrive -VMName $VMName -Path $VMISOPath
}
# Set VM Processor Count and Disable AutomaticCheckpoints
Set-VMProcessor -VMName $VMName -Count $VMProcessorCount -ExposeVirtualizationExtensions $true
if ($StaticMemory) {
Set-VM -AutomaticCheckpointsEnabled $false -VMName $VMName -StaticMemory
} else {
Set-VM -AutomaticCheckpointsEnabled $false -VMName $VMName
}
Start-VM $VMName
}
Create-VM -VMName "Ubuntu 22.04" -VMISOPath "E:\系统盘\Ubuntu Server 22.04.3\ubuntu-22.04.3-live-server-amd64.iso" -VMGen 1
蓝奏云下载: