Question

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

    }
Était-ce utile?

La 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.

Autres conseils

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top