【问题标题】:handling net use error messages with powershell使用 powershell 处理网络使用错误消息
【发布时间】:2016-09-01 13:06:04
【问题描述】:

我正在使用一个简单的 net use 命令来映射网络驱动器

net use \\$HOSTIP $PASSWD /user:$UNAME

我必须使用 net use 而不是 New-PSDrive,因为脚本在多个实例中运行在 400 多台机器上,而且不可行。 我想过滤错误消息然后 net use return like

System error 64 has occurred.

System error 67 has occurred.

我该怎么做?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您可以执行以下操作:

    #set process startup info (redirect stderr)
    $pinfo = new-object System.Diagnostics.ProcessStartInfo
    $pinfo.Filename = "net.exe"
    $pinfo.UseShellExecute = $false
    $pinfo.Arguments = @("use","\\$($HOSTIP)","$($PASSWD)","/user:$($UNAME)")
    $pinfo.redirectstandardError = $true
    #start process and wait for it to exit
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo
    $p.start() | out-null
    $p.waitforexit()
    #check the returncode
    if($p.exitcode -ne 0){
        #rc != 0 so we grab the stderr output
        $err = $p.standardError.ReadToEnd()
        #first line of the output contains the string from your question, matching it against regex
        if($err[0] -match "System error ([0-9]*) has occurred"){
            #switching the error code
            switch($Matches[1]){
                64 {do-something64;break;}
                67 {do-something67;break;}
            }
        }
    }
    

    这应该可以解决问题,尽管我无法说明它的性能如何,但您必须尝试一下。如果输出可能与您在问题中发布的字符串不同,您将不得不编写自己的正则表达式来处理它们。

    请记住,net 的输出是本地化的,因此我示例中的正则表达式在系统语言不是英语的系统上不起作用。

    希望有帮助

    【讨论】:

      【解决方案2】:

      使用cmdstderr 重定向到stdout

      $log = cmd /c "2>&1" net use \\$HOSTIP $PASSWD /user:$UNAME
      

      现在变量包含一个字符串数组(2 个带文本,2 个空):

      发生系统错误 53。

      找不到网络路径。

      你可以解析它:

      $log = cmd /c "2>&1" net use \\$HOSTIP $PASSWD /user:$UNAME
      if ($LASTEXITCODE -and $log -join "`n" -match '^.+?(\d+).+?\n+(.+)') {
          $errCode = [int]$matches[1]
          $errMessage = $matches[2]
      }
      

      【讨论】:

        猜你喜欢
        • 2018-07-17
        • 1970-01-01
        • 2014-10-02
        • 1970-01-01
        • 1970-01-01
        • 2016-11-30
        • 2016-12-14
        • 2011-10-20
        • 2021-07-16
        相关资源
        最近更新 更多