Thursday, March 30, 2017

Use PowerShell to Create a Switch and VM


This PowerShell script copies an ISO to a local directory, creates a Switch bound to the ethernet adapter then creates a virtual machine and attaches it to the switch.

<# Create Hyper-V folder and copy ISO #>
$VMLOC = "C:\Users\Public\Documents\Hyper-V"
Write-Host "Copying ISO. Please Wait"
Copy-Item .\CMBOOT.iso $VMLOC -Force > $nul
Write-Host ""
Write-Host "ISO Copied"

<# Create Hyper-V Switch #>
Import-Module Hyper-V
$ethernet = Get-NetAdapter -Name ethernet
New-VMSwitch -Name External_Switch -NetAdapterName $ethernet.Name -AllowManagementOS $true -Notes ‘Parent OS, VMs, LAN’

<# Create Hyper-V Machine and connect to it #>
$VMName = "Windows_7_VM"
$RAM = 4GB
$VHDSize = 120GB
$VMSwitch = "External_Switch"
$W7ISO = "$VMLOC\CMBOOT.iso"
New-VM -Name $VMName -Path $VMLOC -MemoryStartupBytes $RAM -NewVHDPath "$VMLOC\$VMName.vhdx" -NewVHDSizeBytes $VHDSize -Switchname $VMSwitch
Set-VMDvdDrive -VMName $VMName -Path $W7ISO

No comments:

Post a Comment