通过Powershell调用NET

通过Powershell调用NET

本文介绍了通过Powershell调用NET USE命令时如何获取退出代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the powershell snippet below which I intend to close connections to a shared locations by calling NET.exe tool:

 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 ..."
        }

问题:如何检查调用的网络使用"命令是否工作正常,没有任何错误?如果有的话,我该如何捕获错误代码.

QUESTION:How can I check if the invoked Net Use command worked fine without any errors? And if there is, how can I catch the error code.

推荐答案

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

You can test the value of $LASTEXITCODE. That will be 0 if the net use command succeeded and non-zero if it failed. 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命令本身的错误输出,并对其进行处理.

You might also choose to capture the error output from the net use command itself and do something with it.

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.

这篇关于通过Powershell调用NET USE命令时如何获取退出代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 23:04