How can I use powershell to check if a mapped drive is open / connected?

10,171

The script is probably waiting for permission to delete the connection

e.g.

M:\>net use m: /delete
There are open files and/or incomplete directory searched pending on the connection to m:.

Is it OK to continue disconnection and force them closed (Y/N) [N]:

You need to provide the permission on the command line

e.g

M:\>net use m: /delete /yes
There are open files and/or incomplete directory searched pending on the connection to m:.

m: was deleted successfully

or in your case

if exist %1 net use %1 /del /yes
Share:
10,171

Related videos on Youtube

Ben
Author by

Ben

Updated on September 17, 2022

Comments

  • Ben
    Ben almost 2 years

    I am writing a login script which unmaps and remaps some drives.

    The powershell calls a small batch file for the actual unmapping, as Powershell seems a bit flaky at reliably mapping the drives.

    The code I am using is:

        $arrDrives = "m:","n:","o:","p:","q:","r:","s:","u:","v:","x:","y:"
        foreach ($drive in $arrDrives) { 
            if (test-path $drive) {
                UpdateSubHeading ("Removing drive " + $drive)
                c:\bin\removeDrive.bat $drive } 
        }
    

    And the batch file it calls is just:

    if exist %1 net use %1 /del
    

    This all works fine, unless there is an open connection to the drive it is trying to unmap. If the user has a file open, then it hangs.

    Is there a way I can check if there are any connections open to the mapped drive before I try and unmap it, and skip unmapping it if there are?

    Thanks,

    Ben