Although I don't understand why this can happen, you seem to have some NICs that are connected to a dvSwitch portgroup but that do not have a portkey. We can filter those out with a Where-clause.
See if this variation runs error-free
$nicTypes = "VirtualE100","VirtualE100e","VirtualPCNet32","VirtualVmxnet","VirtualVmxnet2","VirtualVmxnet3" $ports = @{} $pgName = "MyPG"
# Get all the portkeys on the portgroup
$pg = Get-VirtualPortGroup -Distributed -Name $pgName $pg.ExtensionData.PortKeys | %{$ports.Add($_,$pg.Name)} # Remove the portkeys in use Get-View
$pg.ExtensionData.Vm | %{ $nic = $_.Config.Hardware.Device | where {$nicTypes -contains $_.GetType().Name -and $_.Backing.GetType().Name -match "Distributed"} $nic | where {$_.Backing.Port.PortKey} | %{$ports.Remove($_.Backing.Port.PortKey)} } # Assign the first free portkey
$key = ($ports.Keys | Sort-Object)[0] $key