0

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

    }
pencilCake
  • 51,323
  • 85
  • 226
  • 363

2 Answers2

1

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.

CB.
  • 58,865
  • 9
  • 159
  • 159
  • In the if clause you test if there is an open connection to the shared location. I got it. And in the following line do you get the mapped drive names into $u and only after then you Remove? Am I correct? – pencilCake Jun 05 '13 at 12:25
  • @pencilCake yes, you test if there are opened files and based on the result remove the mapped drive or do something else.. – CB. Jun 05 '13 at 12:32
  • Ok. Makes sens but what if the localname is EMPTY -which is my case. – pencilCake Jun 05 '13 at 12:33
  • um.. how can be a networkdrive without a unit letter? mumble.. mumble – CB. Jun 05 '13 at 12:36
  • yes. Cooorect. For example I connected to this shared folder via File Explorer.. So how can I disconnect in such case? – pencilCake Jun 05 '13 at 12:42
  • you can still use `net use \\poooh.fooo.boo.com\MyFolder /delete` – CB. Jun 05 '13 at 13:02
0

Use Test-Path cmdlet. It will return $false if the path is not valid. That is, the path is non-existing or insufficient user rights prevent access. Like so,

PS C:\> test-path k: # There is no k: drive
False
PS C:\> test-path \\ServerWithoutPermissions\c$
False
PS C:\> test-path \\NonExistingHost\share
False
vonPryz
  • 22,996
  • 7
  • 54
  • 65
  • But I do not know with what letter it was mapped to "\\poooh.fooo.boo.com\MyFolder" user="FOO\winnie" password="12345678" – pencilCake Jun 05 '13 at 11:59