I was working on a PowerShell script that pulls errors out of the Event Log into an array from a list of servers. The script will then report the errors for each server, or will report that no errors were found, as seen in a condensed version of the script below:
$events = Get-EventLog -Computer $ComputerName – Logname Application
IF ($errors.Count -lt 1)
{Write-Output “No errors were found from the application log on $ComputerName”}
This seemed to work most of the time, but on the outputted report there were a few servers that would show an error taken from the Event Log and also state there were no errors found. The first thinig I noticed was that this only happened when a single error was returned from the Event Log. So I thought maybe something was wrong with my logic in the if statement and the use of the count property of the array. The actual problem was that for the servers with only one error, the $errors variable was not an array since it only contained a single value.
In order to ensure the $errors variable was an array, I had to designate it as an array using the @ symbol. I already knew I could declare a new empty array using $newarray = @(), I just didn’t apply that knowledge to this script until I ran into problems and had to do some research online. Below is the new condensed excerpt from my script:
$events = @(Get-EventLog -Computer $ComputerName – Logname Application)
IF ($errors.Count -lt 1)
{Write-Output “No errors were found from the application log on $ComputerName”}
Now $errors will be an array, whether it has just one value, more than one value, or even no values at all.
So when working with an array, make sure your array is an array.
Nice post to introducing array is an array.