Skip to content

Instantly share code, notes, and snippets.

@rayterrill
Created October 7, 2017 17:47
Show Gist options
  • Save rayterrill/833bf97b4824dfe1af576114aa4b6132 to your computer and use it in GitHub Desktop.
Save rayterrill/833bf97b4824dfe1af576114aa4b6132 to your computer and use it in GitHub Desktop.
Tests VLANs in VMWare using PowerShell, Pester, and PowerCLI by swapping a VM into different networks, setting an IP, and verifying connectivity.
Connect-VIServer -Server YOUR_VCENTER_SERVER | Out-Null
#build a credential object to connect to the VM at the OS level to switch the network settings
$secpwd = ConvertTo-SecureString "PASSWORD_GOES_HERE" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("ACCOUNT_GOES_HERE", $secpwd)
#set a hash tables of VMWare networks and an IP address in each network
$networks = @{
"VLAN1" = "192.168.1.5"
"VLAN2" = "192.168.2.5"
}
#grab the network adapter for our test VM
$networkAdapter = Get-NetworkAdapter -VM VLANTESTER
Describe "Check VLANs" {
foreach ($h in $networks.Keys | Sort) {
It "VLAN $($h)" {
#set the machine's VLAN
Set-NetworkAdapter -NetworkAdapter $networkAdapter -NetworkName $h -WakeOnLan:$true -StartConnected:$true -Connected:$true -Confirm:$false | Out-Null
#nuke the old IP
Invoke-VMScript -VM VLANTESTER -ScriptText "Get-NetIPAddress | Where-Object {`$_.InterfaceIndex -eq '12' -AND `$_.AddressFamily -eq 'IPv4'} | Remove-NetIPAddress -Confirm:`$false" -GuestCredential $cred | Out-Null
#nuke the old gateway
Invoke-VMScript -VM VLANTESTER -ScriptText "Get-NetRoute | Where-Object {`$_.NextHop -ne '0.0.0.0' -AND `$_.DestinationPrefix -eq '0.0.0.0/0'} | Remove-NetRoute -Confirm:`$false" -GuestCredential $cred | Out-Null
#calculate the gateway
$ip = $networks[$h]
$sep = $ip.lastindexof(".")
$gateway = $ip.substring(0,$sep) + ".254"
#configuring the gateway
Invoke-VMScript -VM VLANTESTER -ScriptText "New-NetIPAddress -InterfaceIndex 12 -IPAddress $ip -PrefixLength 24 -DefaultGateway $gateway" -GuestCredential $cred | Out-Null
Start-Sleep 3
#testing pings to the new ip
Test-Connection $ip -Quiet |
Should be $true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment