VMware Cloud Community
NeoKumar
Enthusiast
Enthusiast
Jump to solution

Delete virtualportgroup if not connected to VM

I need help to find a way to check if port is connected to a VM, if not connected then delete port. for deletion part i am using below script. but need assistance to check if its connect to any vm, if not connected delete

$esxinames = Get-Content -Path c:\vmhostfile.txt

ForEach ($servers in $esxinames)
{
Get-VMHost $servers | Get-VirtualPortGroup -Name "portname" | Remove-VirtualPortGroup -Confirm:$false
}

also can the script be -RunAsync, for some reason it was not accepting -RunAsync at end of script.

0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

Something like this?

$esxinames = Get-Content -Path c:\vmhostfile.txt

ForEach ($servers in $esxinames) {
    $pg = Get-VMHost $servers | Get-VirtualPortGroup -Name "portname"
    if($pg.ExtensionData.Port.Count -eq 0){
        Remove-VirtualPortGroup -VirtualPortGroup $pg -Confirm:$false
    }
    else{
        Write-Host "Portgroup $($pg.Name) is in use"
    }
}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

5 Replies
LucD
Leadership
Leadership
Jump to solution

You could do
PS: the Remove-VirtualPortgroup cmdlet doesn't have the RunAsync switch

$esxinames = Get-Content -Path c:\vmhostfile.txt

ForEach ($servers in $esxinames) {
    Get-VMHost $servers | Get-VirtualPortGroup -Name "portname" | 
        where { $_.ExtensionData.Port.Count -eq 0 } |
        Remove-VirtualPortGroup -Confirm:$false
}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

NeoKumar
Enthusiast
Enthusiast
Jump to solution

Hi LucD,
can we use If and else loop,

just to output in "else" that "vmname" is used and cannot be deleted.

Sorry hope am not asking much

Tags (1)
0 Kudos
LucD
Leadership
Leadership
Jump to solution

"vmname", I suspect you mean portgroup?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
LucD
Leadership
Leadership
Jump to solution

Something like this?

$esxinames = Get-Content -Path c:\vmhostfile.txt

ForEach ($servers in $esxinames) {
    $pg = Get-VMHost $servers | Get-VirtualPortGroup -Name "portname"
    if($pg.ExtensionData.Port.Count -eq 0){
        Remove-VirtualPortGroup -VirtualPortGroup $pg -Confirm:$false
    }
    else{
        Write-Host "Portgroup $($pg.Name) is in use"
    }
}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

NeoKumar
Enthusiast
Enthusiast
Jump to solution

thank you, it works as needed.

0 Kudos