【问题标题】:Powershell Get_EventLog for multiple servers用于多个服务器的 Powershell Get_EventLog
【发布时间】:2017-04-17 18:34:18
【问题描述】:

我是一名 SQL DBA,不熟悉 Powershell,目前负责系统管理员职责

我需要在我的服务器上查询错误日志以获取错误和警告。

使用我自己的 Google-fu 和 this 线程的帮助,我能够得到这个工作:

 $computers = Get-Content "C:\Servers\ServerList_Short.txt"; 

# QUERY COMPUTER SYSTEM EVENT LOG
foreach($computer in $computers)

{        
     Get-EventLog -ComputerName $computer -LogName System -EntryType "Error","Warning" -After (Get-Date).Adddays(-7) `
     | Select-Object -Property machineName, EntryType, EventID, TimeGenerated, Message `
     | Format-Table -Property MachineName, TimeGenerated, EntryType, Source,  Message -AutoSize ;

}

我目前缺少的是如何在我的 .txt 文件中捕获离线的服务器,忽略它并移至下一个。之后,我将努力将所有这些转储到 SQL 表、results.txt 等中。

感谢您的帮助:)]

凯文3NF

【问题讨论】:

    标签: windows powershell get-eventlog


    【解决方案1】:

    有几种不同的方法可以处理这个问题,但我建议将Test-ConnectionTry/Catch 结合使用,Test-Connection 将使它成为这样,这样您就只尝试查询响应 ping 的服务器,然后Try/Catch 将处理可能出现的任何其他错误。

    foreach($computer in $computers)
    
    {        
     if(Test-Connection $computer -Quiet -Count 1){
        Try {
            Get-EventLog -ComputerName $computer -LogName System -EntryType "Error","Warning" -After (Get-Date).Adddays(-7) `
         | Select-Object -Property machineName, EntryType, EventID, TimeGenerated, Message `
         | Format-Table -Property MachineName, TimeGenerated, EntryType, Source,  Message -AutoSize
        } Catch {
            Write-Verbose "Error $($error[0]) encountered when attempting to get events from  $computer"
        }
     } else {
        Write-Verbose "Failed to connect to $computer"
     }
    
    }
    

    【讨论】:

    • 谢谢!我有一个用于测试的 3 个服务器列表,一个不存在。在取得良好结果后得到了这个:Test-Connection:无法验证参数'ComputerName'的参数。参数为 null 或空。提供一个不为 null 或空的参数,然后重试该命令。
    • 该错误意味着您的文件末尾有一个空行,您可以通过将test-connection 放在try/catch 内的嵌套nad 来克服它,或者只是确保您的文件没有'末尾没有空行,无论是在前端还是通过执行 $computers = $computers | Where-object {$_} 这将消除数组中的空值
    • 完美...必须有一个 CR;LF...删除了它,运行在我的完整服务器列表中并且它有效...谢谢!!!
    猜你喜欢
    • 1970-01-01
    • 2020-10-17
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多