我有下面的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命令是否正常运行而没有任何错误?如果有,我怎么能抓住错误代码。
答案 0 :(得分:3)
您可以测试$LASTEXITCODE
的值。如果net use
命令成功则为0,如果失败则为非零。 e.g。
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.