5

我有下面的 powershell 片段,我打算通过调用 NET.exe 工具来关闭与共享位置的连接:

 if ($connectionAlreadyExists -eq $true){
            Out-DebugAndOut "Connection found to $location  - Disconnecting ..."
            Invoke-Expression -Command "net use $location /delete /y"  #Deleting connection with Net Use command
            Out-DebugAndOut "Connection CLOSED ..."
        }

问题:如何检查调用的 Net Use 命令是否正常工作且没有任何错误?如果有,我怎样才能捕捉到错误代码。

4

1 回答 1

5

您可以测试 的值$LASTEXITCODE。如果net use命令成功,则为 0,如果失败,则为非零。例如

PS C:\> net use \\fred\x /delete
net : The network connection could not be found.
At line:1 char:1
+ net use \\fred\x /delete
+ ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (The network con...d not be found.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

More help is available by typing NET HELPMSG 2250.

PS C:\> if ($LASTEXITCODE -ne 0) { Write-Error "oops, it failed $LASTEXITCODE" }
if ($LASTEXITCODE -ne 0) { Write-Error "oops, it failed $LASTEXITCODE" } : oops, it failed 2
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

您也可以选择从net use命令本身捕获错误输出并对其进行处理。

PS C:\> $out = net use \\fred\x /delete 2>&1

PS C:\> if ($LASTEXITCODE -ne 0) { Write-Output "oops, it failed $LASTEXITCODE, $out" }
oops, it failed 2, The network connection could not be found. 
More help is available by typing NET HELPMSG 2250.
于 2014-03-18T13:27:00.500 回答