Thanks, LucD. I am using this function to help with a vCenter migration in which the destination dvSwitch doesn't have any connected VMs. You are correct in your statement that the portgroup in which I received the error doesn't have any VMs. I was able to determine this by issuing the following commands from the function:
$pg = Get-VirtualPortGroup -Distributed -Name $PortGroup
Get-View $pg.ExtensionData.Vm(returns nothing)
It is interesting that most of the VMs worked and that a few didn't. I'm not sure what information you need, but here is some screenshots of the dvSwitch:
Here is how I'm using the function when trying to add the VM NIC:
$vmPortKey = Get-dvPgFreePort -PortGroup "${NetworkName}" -Number 1
get-networkadapter -VM "${VM}" | Set-NetworkAdapter -DistributedSwitch $VDS -PortKey $vmPortKey -WakeOnLan:$true -StartConnected:$true -Connected:$true -Confirm:$false
... where "NetworkName" is equal to "10.29.0.0/16_VLAN2_SSH-Workstations" for one of the VMs that is failing. Also keep in mind that we have might have multiple dvSwitches in the same environment.
I hope I didn't leave anything out, and that his information helps! You have been a critical to my migration, and it is greatly appreciated!
Charles