您可以测试 的值$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.