VMware - Scripting - PowerCLI - VMs with portgroup

# Export-VMsWithPortGroupAndVlan.ps1
# Exports a list of VM names with network adapter and VLAN ID.
 
$strCsvFile = "VMs-with-portgroup.csv"
 
$objVMs = Get-VM | Where-Object {$_.PowerState -eq "PoweredOn"}
$objVPGrp = Get-VirtualPortGroup | Sort-Object Name -Unique
$objResult = @()
foreach ($objVM in $objVMs) {
  $objNetworkAdapters = Get-NetworkAdapter -VM $objVM
  foreach ($objNetworkAdapter in $objNetworkAdapters) {
    $objTmp = @{} | Select-Object VMName,NetworkAdapter,PortGroup,VLAN
    $objTmp.VMName = $objVM.Name
    $objTmp.NetworkAdapter = $objNetworkAdapter.Name
    $objTmp.PortGroup = $objNetworkAdapter.NetworkName
    $objTmp.VLAN = ($objVPGrp | Where-Object {$_.Name -eq "$($objNetworkAdapter.NetworkName)"}).VLanId
    $objResult += $objTmp
  }
}
$objResult | Sort-Object VMName | Export-Csv -Path "$strCsvFile" -NoTypeInformation