windowspowershellget-eventlog

Powershell Get_EventLog for multiple servers


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


Solution

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