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

Add every member of the Users group to the Hyper-V Administrators group.


I recently had a challenge to make Hyper-V available to everyone on a PC and it had to work in other languages. So net localgroup is out since you have to use the SID of the groups. Here is the PowerShell script I used for that.






#Gets all of the local groups
$GetGroups = Get-WmiObject -Query "select * from win32_group where Domain='$env:computername'"

#Selects the Hyper-V Administrators group from the array using the well known SID
$hyperVgroup= $GetGroups | Where-Object {$_.SID -eq 'S-1-5-32-578'}
$HVgroupName= $hyperVgroup.Name

#Selects the Users group from the array using the well known SID
$UserGroup = $GetGroups | Where-Object {$_.SID -eq 'S-1-5-32-545'}
$Usergroupname = $UserGroup.Name

#Gets the members of the Users group.
$Group = [ADSI]"WinNT://$env:Computername/$usergroupname,group"
if ($Group.Path)
            {
                $Members = @($Group.psbase.Invoke("Members"))
                [Array]$MemberNames = $Members |
                    ForEach-Object {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)} }

<#Takes the members from the Users group and puts them into the Hyper-V Admin group.
This will result in errors since some of the accounts are not "NT Authority" #>
foreach($member in $MemberNames){
([adsi]”WinNT://./$HVgroupName,group”).Add(“WinNT://NT Authority/$member,user”) > $null
}