Today I had to come up with a way of looking for a certain eventID in the event logs of our VDI estate, using get-winevent.
I had a few challenges which I managed to work around;
Challenge 1
When a given PC had multiple results, referencing the first record as $logonevents[0] was fine.
When a given PC had only one result, referencing the first (only) record as $logonevents[0] caused an error, as it wanted to be referenced as $logonevents.
Short of forcing the datatype into an array (which I couldn’t work out how to do and wasn’t sure would do the trick), I used an IF statement to check if $logonevents[0] existed, and use $logonevents if it didn’t;
if ($logonevents.timecreated) {$info.lastlogin = $logonevents.timecreated} else {$info.lastlogin = $logonevents[0].timecreated}
Challenge 2
My script didn’t provide a value for “last logon event” if there wasn’t one to find, but of course this value was also blank if the query failed (i.e. the VM was off or not working correctly).
I wanted a way to set the result to “None found” if the error was “Get-WinEvent : No events were found that match the specified selection criteria.” – I had 90% of the thinking for this but needed my ex-colleague and powershell guru Stephen Spike to force me to look at it a bit harder. The resulting code was;
#resets $error variable to nothing
$error.clear()
#looks for event
$logonevents = Get-WinEvent -computername $hostname -FilterHashtable @{logname="system"; id="7001"; providername="microsoft-windows-winlogon"}
#sets result to “None found” if appropriate
if ("$Error[0]".Contains("No events were found")) {$info.lastlogin = "No logon events found"}
No comments:
Post a Comment