0

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

Community
  • 1
  • 1
Kevin3NF
  • 113
  • 1
  • 8

1 Answers1

2

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

}
Mike Garuccio
  • 2,588
  • 1
  • 11
  • 20
  • thanks! I have a 3 server list for testing, one doesn't exist. Got this back after the good results: Test-Connection : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again. – Kevin3NF Dec 02 '16 at 20:17
  • 1
    The error means you have a blank line at the end of your file, you can overcome it by chaning the nesting nad putting the `test-connection` inside of the `try/catch` or just make sure your file doesn't have blank lines at the end, either on the front-end or by doing a `$computers = $computers | Where-object {$_}` which will elminate null values from your array – Mike Garuccio Dec 02 '16 at 20:19
  • Perfect...must have had a CR;LF...removed that, ran against my full server list and it worked...thanks!!! – Kevin3NF Dec 02 '16 at 21:07