Powershell Get_EventLog for multiple servers

半腔热情 提交于 2019-12-12 03:43:49

问题


I'm a SQL DBA, n00b to Powershell, tasked with sysadmin duties at the moment

I need to query error logs across my servers for Errors and Warnings.

Using my own Google-fu and help from this thread I was able to get this working:

 $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 ;

}

What I am missing at the moment is how to trap for a server in my .txt file that is offline, ignore it and move to the next one. After that, I will be working to dump all of this to a SQL table, results.txt, etc.

Thanks for any help :)]

Kevin3NF


回答1:


There are a few different ways to handle this but I'd recommend combining a Test-Connection with a Try/Catch, the Test-Connection will make it so that you only try to query the servers which respond to ping and then the Try/Catch will handle any other errors that may come along.

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"
 }

}


来源:https://stackoverflow.com/questions/40939147/powershell-get-eventlog-for-multiple-servers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!