【问题标题】:Easily hide error given by PS and show message轻松隐藏 PS 给出的错误并显示消息
【发布时间】:2013-06-25 01:45:57
【问题描述】:

我目前正在完成我的 PS 脚本以从服务器列表中获取时间并将它们导出到 .txt 文件。问题是有连接问题的服务器只给出了一个 PS 错误。我希望有连接问题的服务器也被记录下来,并且只是一条消息,即“服务器服务器名称无法访问”。非常感谢您的帮助!

cls
$server = Get-Content srvtime_list.txt
Foreach ($item in $server)
{
 net time \\$item | find /I "Local time" >> srvtime_result.txt
}

【问题讨论】:

    标签: powershell time export-to-text


    【解决方案1】:

    我可能会稍微重写你的代码:

    Get-Content srvtime_list.txt |
      ForEach-Object {
        $server = $_
        try {
          $ErrorActionPreference = 'Stop'
          (net time \\$_ 2>$null) -match 'time'
        } catch { "Server $server not reachable" }
      } |
      Out-File -Encoding UTF8 srvtime_result.txt
    

    【讨论】:

    • 这就是我要寻找的。它的速度很快,因为它使用净时间,而且它输出我需要的结果。谢谢!为了只有时区和服务器的本地时间,我进行了一次更正:-match 'Local Time'
    【解决方案2】:

    除了回答您的问题之外,还有其他/更好的方式来获得时间(正如其他人所建议的那样):

    1. 您可以通过将错误流重定向到 null 来抑制错误。
    2. 检查 $LASTEXITCODE 变量,除 0 以外的任何结果都表示命令未成功完成。

      Get-Content srvtime_list.txt | Foreach-Object{
      
         net time \\$_ 2>$null | find /I "Current time" >> srvtime_result.txt
      
         if($LASTEXITCODE -eq 0)
         {
             $result >> srvtime_result.txt
         }
         else
         {
          "Server '$_' not reachable" >> srvtime_result.txt
         }        
      

      }

    【讨论】:

    • 不知道为什么,但它不适用于net time 部分。但是感谢您对如何处理错误的解释,这真的很有帮助。
    【解决方案3】:

    我会这样做:

    Get-Content srvtime_list.txt | %{
       $a = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $_ -erroraction 'silentlycontinue'
       if ($a) { "$_ $($a.ConvertToDateTime($a.LocalDateTime))"  } else { "Server $_ not reachable" }
    } | Set-Content srvtime_result.txt
    

    【讨论】:

    • 它可以工作,但它的过程很慢而且它不显示时区。
    【解决方案4】:

    使用Test-Connection cmdlet 验证远程系统是否可访问。

    cls
    $server = Get-Content srvtime_list.txt
    Foreach ($item in $server)
    {
     if (test-connection $item) {
         net time \\$item | find /I "Local time" >> srvtime_result.txt
        } else {
       "$item not reachable" | out-file errors.txt -append
    }
    }
    

    但是您可以在纯 Powershell 中执行此操作,而无需借助 net time - 使用 WMI。这是未经测试的,因为我目前没有方便的 Windows,但它至少有 90%。

    cls
    $server = Get-Content srvtime_list.txt
    $ServerTimes = @();
    Foreach ($item in $server)
    {
     if (test-connection $item) {
         $ServerTimes += Get-WMIObject -computername $name win32_operatingsystem|select systemname,localdatetime 
        } else {
       "$item not reachable" | out-file errors.txt -append
    }
    }
    $ServerTimes |Out-File srvtime_result.txt
    

    【讨论】:

    • 它可以工作,但是这个过程的 WMI 结果很慢,而且它会将结果分成两个文件。不过没关系,谢谢!
    • 你可以改变我写的内容来创建一个文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多