Created
August 15, 2018 15:44
-
-
Save onyxhat/9ee7f6116c4a367c7d7a19feabdf7460 to your computer and use it in GitHub Desktop.
Hyper-V script to Automate creation of Linux VMs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$Settings = New-Object PsObject -Property @{ | |
Name = Read-Host "VM Name" | |
vCPU = Read-Host "vCPU Count" | |
MemoryStartupBytes = [int]$(Read-Host "GB of RAM") * 1GB | |
ImgSrc = Read-Host "Source VHD Location" | |
} | |
$vmhost = Get-VMHost | |
if ((Get-VM -Name $Settings.Name -ErrorAction SilentlyContinue) -or (Test-Path -Path "$($vmhost.VirtualHardDiskPath)\$($Settings.Name).vhdx")) { | |
throw "VM or Virtual Disk Already Exists" | |
} | |
Write-Host "Cloning VM Base-Image..." | |
$BaseImage = Get-Item -Path $Settings.ImgSrc | |
$BaseImage | Copy-Item -Destination "$($vmhost.VirtualHardDiskPath)\$($Settings.Name).vhdx" -Force | |
Write-Host "Creating VM..." | |
$VM = New-VM -Name $Settings.Name -MemoryStartupBytes $Settings.MemoryStartupBytes -BootDevice VHD -VHDPath "$($vmhost.VirtualHardDiskPath)\$($Settings.Name).vhdx" -Path $vmhost.VirtualMachinePath -Generation 1 -Switch "vNet - External" | |
$VM | Set-VMProcessor -Count $Settings.vCPU | |
Write-Host "Configuring VM..." | |
$VM | Add-VMNetworkAdapter -SwitchName "vNet - Internal" -DynamicMacAddress | |
$VM | Get-VMNetworkAdapter | ? { $_.SwitchName -eq "vNet - Internal" } | Set-VMNetworkAdapterVlan -Access -VlanId 2 | |
$VM | Enable-VMIntegrationService -Name "Guest Service Interface" | |
Write-Host "Starting VM..." | |
$VM | Start-VM | |
Do { | |
#Requires OS has Hyper-V Integration Services installed to work properly (timeout can be added) | |
$IpAddresses = $VM | Select-Object -ExpandProperty NetworkAdapters | Select-Object IPAddresses, Status | |
} | |
Until ($IpAddresses.IPAddresses -ne $null) | |
$Settings | Add-Member -MemberType NoteProperty -Name IpAddresses -Value $IpAddresses | |
$Settings | Add-Member -MemberType NoteProperty -Name VM -Value $VM | |
#Settings object returned with appended objects containing IP Addresses for VM and complete VM object | |
return $Settings | |
<# | |
Using the Settings object you can automate SSH call to host to handle rename and running updates | |
When rebooting for changes to take effect - use the Hyper-V cmdlets Stop-VM and Start-VM for a graceful shutdown | |
Restart-VM does not allow the guest OS to gracefully quiesce. | |
#> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment