如何使用 powershell 检查映射驱动器是否打开/连接?

Ben*_*Ben 3 powershell network-share login-script

我正在编写一个登录脚本,它取消映射并重新映射一些驱动器。

powershell 调用一个小的批处理文件来进行实际的取消映射,因为 Powershell 在可靠地映射驱动器方面似乎有点不稳定。

我正在使用的代码是:

    $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 } 
    }
Run Code Online (Sandbox Code Playgroud)

它调用的批处理文件只是:

if exist %1 net use %1 /del
Run Code Online (Sandbox Code Playgroud)

这一切正常,除非有一个到它试图取消映射的驱动器的开放连接。如果用户打开了一个文件,它就会挂起。

在我尝试取消映射之前,有没有办法检查是否有任何连接打开到映射驱动器,如果有则跳过取消映射?

谢谢,

use*_*517 5

脚本可能正在等待删除连接的权限

例如

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]:
Run Code Online (Sandbox Code Playgroud)

您需要在命令行上提供权限

例如

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
Run Code Online (Sandbox Code Playgroud)

或者在你的情况下

if exist %1 net use %1 /del /yes
Run Code Online (Sandbox Code Playgroud)