Search code examples
.netpowershellpowershell-2.0powershell-3.0net-use

How do I disconnect form an existing connection to a network location in PowerShell?


I disconnect from ALL device in Powershell like this:

 Invoke-Expression -Command "net use * /delete /y"

And I need to do it for particular devices instead of disconnecting from ALL.

Question: How can I TEST if there is already a connection to a particular network location and DISCONNECT (delete connection) if there is?

What I am trying to achieve in general is something like this:

IF (there is already a connection to a network drive with below details)

   "\\poooh.fooo.boo.com\MyFolder" user="FOO\winnie" password="12345678"

THEN 
    {

      Disconnect from this network drive #via NET USE I guess
      And CREATE a PS-DRIVE to the same network location

    }

Solution

  • You can try this:

    $nc = gwmi Win32_NetworkConnection 
    
    if  (( $nc  | select -expa remotename ) -contains '\\poooh.fooo.boo.com\MyFolder' )
    {
    $u =  $nc | ? { $_.remotename -eq '\\poooh.fooo.boo.com\MyFolder' } | select -expa localname
    $netobj=New-Object -ComObject WScript.Network
    $netobj.RemoveNetworkDrive($u)
    
    }
    

    The remove may fail if connection have files opened.