How to obtain exit code when I invoke NET USE command via Powershell?

自作多情 提交于 2019-12-14 03:49:47

问题


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.


回答1:


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

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.


来源:https://stackoverflow.com/questions/22475361/how-to-obtain-exit-code-when-i-invoke-net-use-command-via-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!