【问题标题】:How to obtain exit code when I invoke NET USE command via Powershell?通过 Powershell 调用 NET USE 命令时如何获取退出代码?
【发布时间】:2014-04-23 21:32:29
【问题描述】:

我有下面的 powershell sn-p,我打算通过调用 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 命令是否工作正常且没有任何错误?如果有,我怎样才能捕捉到错误代码。

【问题讨论】:

    标签: powershell networking windows-server-2008 shared-directory


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-04
      • 2016-10-08
      • 2020-01-13
      • 2023-04-09
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2018-11-04
      相关资源
      最近更新 更多