As part of the migration I’m working on, we needed to add a whole bunch of Virtual Port Groups with associated VLANs to the servers. The following script could do this in a few minutes (although Host Profiles would accomplish much the same thing, we’re not running Enterprise).

# Sets up virtual port groups on all hosts connected to a specific vCenter Server

# Name of vCenter Server
$strVCenterServer = "your.vCenter.Server"

# VLANs and associated VPGs
$ArrVLANs = @{
	"123" = "vlanA";
	"456" = "vlanB";
	"789" = "vlanC";

# Connect to the vCenter Server
Connect-VIserver -Server $strVCenterServer

# Loop through the VLAN/VPG pairs
foreach($objVLAN in ($ArrVLANs.Keys | Sort-Object)){
	# Loop through the hosts
	foreach ($objHost in (Get-VMHost | Sort-Object)){
		# Create the VPG with the VLAN as specified in the array above, on the switch called "VMSwitch" on the current host
		# Remove the "-WhatIf" tag from the end of the following line to "arm" the script
		New-VirtualPortGroup -Name $strNewVPG -VirtualSwitch (Get-Virtualswitch -VMHost $objHost | Where-Object { $_.Name -match "VMswitch" }) -VLanId $strNewVlanTag
		# Write what we've just done to screen
		Write-Output -InputObject ("Adding Virtual Port Group $($ArrVLANs[$objVLAN]) with VLAN Tag $objVLAN to $objHost")
# Disconnect the session from the host
Disconnect-VIServer -Confirm:$False

Although this isn’t a complicated script, it was the first time I’ve used hash tables (thanks to PowerShell.Com’s excellent page), so I thought I’d share.