Add port group to all VMHosts with PowerCli

This is the script that I use when I need to add several new port groups to a single VMware cluster.  The script does check for the port group before it tries to add it to the VMhost encase it was already setup.

$NetworkInfo = Import-CSV C:\scripts\logs\NetworkInfo.csv
$ClusterName = "VM_Cluster"
$VMHosts = Get-Cluster $ClusterName | Get-VMHost
Foreach ($network in $NetworkInfo){
    $NewPortSwitch = $network.NewPortSwitch
    $VLANID = $Network.VLANID
    Foreach ($VMHost in $VMHosts){
        IF (($VMHost | Get-VirtualPortGroup -name $NewPortSwitch -ErrorAction SilentlyContinue) -eq $null){
            Write-host "Creating $NewPortSwitch on VMhost $VMHost" -ForegroundColor Yellow
            $NEWPortGroup = $VMhost | Get-VirtualSwitch | Select -last 1 | New-VirtualPortGroup -Name $NewPortSwitch -VLanId $VLANID 
        }
    }
}

Below is the format for the NetworkInfo.csv. You can add as many port groups as you need in to this file and it gets feed into the script.

NetworkInfo.csv
NetworkInfo.csv

– Stuart

3 thoughts on “Add port group to all VMHosts with PowerCli”

  1. Hey Stuart – I just used this script to duplicate network settings on a new vCenter v6.7 cluster I’m building. It worked great, but it needed a minor tweak since we have multiple vSwitches on each host due to iSCSI storage. See below…

    $NetworkInfo = Import-CSV C:\scripts\logs\NetworkInfo.csv
    $ClusterName = “VM_Cluster”
    $VMHosts = Get-Cluster $ClusterName | Get-VMHost
    Foreach ($network in $NetworkInfo){
    $NewPortSwitch = $network.NewPortSwitch
    $VLANID = $Network.VLANID
    Foreach ($VMHost in $VMHosts){
    IF (($VMHost | Get-VirtualPortGroup -name $NewPortSwitch -ErrorAction SilentlyContinue) -eq $null){
    Write-host “Creating $NewPortSwitch on VMhost $VMHost” -ForegroundColor Yellow
    $NEWPortGroup = $VMhost | Get-VirtualSwitch -Name “vSwitch0” | Select -last 1 | New-VirtualPortGroup -Name $NewPortSwitch -VLanId $VLANID
    }
    }
    }

    1. Hello Tim,
      Thanks for the update to the script. We have a plan to get the work environment up to 6.7u1, but it might still be some time before we get it completed.

      -Stuart

      1. The upgrade isn’t too bad. If you use the VCSA it makes it almost painless. I could walk you through it over the phone if you want to. I learned from a couple of mistakes that I wouldn’t want you to repeat. Nothing horrible, but I rebuilt a host that I could have just had the VCSA automagically update.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.