Created
December 9, 2018 18:52
-
-
Save onyxhat/72b9ae20a1e07fba352aefaf1a38ff81 to your computer and use it in GitHub Desktop.
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
Param ( | |
[string]$VMName, | |
[int]$vCPU, | |
[int]$MemoryGB | |
) | |
$Settings = New-Object PsObject -Property @{ | |
Name = $VMName | |
vCPU = $vCPU | |
MemoryStartupBytes = [int]$MemoryGB * 1GB | |
BaseImage = "C:\\Hyper-V\\VHDs\\Base_Image.vhdx" | |
ExternalNet = "vNet - External" | |
InternalNet = "vNet - Internal" | |
} | |
$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.BaseImage | |
$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 $Settings.ExternalNet | |
$VM | Set-VMProcessor -Count $Settings.vCPU | |
Write-Host "Configuring VM..." | |
### This might not work for you if you don't have internal networking setup between VMs and the VMHost | |
#$VM | Add-VMNetworkAdapter -SwitchName $Settings.InternalNet -DynamicMacAddress | |
#$VM | Get-VMNetworkAdapter | ? { $_.SwitchName -eq $Settings.InternalNet } | Set-VMNetworkAdapterVlan -Access -VlanId 2 | |
$VM | Enable-VMIntegrationService -Name "Guest Service Interface" | |
Write-Host "Starting VM..." | |
$VM | Start-VM | |
$timeout = $(Get-Date) + $(New-TimeSpan -Minutes 3) | |
Do { | |
$IpAddresses = $VM | Select-Object -ExpandProperty NetworkAdapters | Select-Object IPAddresses, Status | |
if ($(Get-Date) -gt $timeout) { throw "Failed to get IP Address within timeout." } | |
} | |
Until ($IpAddresses.IPAddresses -ne $null) | |
$Settings | Add-Member -MemberType NoteProperty -Name IpAddresses -Value $IpAddresses | |
return $Settings |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment