当我通过Powershell调用NET USE命令时,如何获取退出代码?

当我通过Powershell调用NET USE命令时,如何获取退出代码?,powershell,networking,windows-server-2008,shared-directory,Powershell,Networking,Windows Server 2008,Shared Directory,下面是powershell代码段,我打算通过调用NET.exe工具来关闭与共享位置的连接: if ($connectionAlreadyExists -eq $true){ Out-DebugAndOut "Connection found to $location - Disconnecting ..." Invoke-Expression -Command "net use $location /delete /y" #Deleting

下面是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命令是否工作正常,没有任何错误?如果有,如何捕获错误代码。

您可以测试
$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
您还可以选择从
netuse
命令本身捕获错误输出,并对其进行处理

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.