Getting Change Events

I wasn’t particularly happy with the script for getting change events on the filesystemwatcher we discussed last time.  As a quick recap we ended up with this

001
002
003
004
Get-Event -SourceIdentifier "File System Changed" | where {($_.EventIdentifier % 2) -eq 1} | foreach {
    "{0}, {1}, {2}" -f   $_.SourceIdentifier, $_.SourceEventArgs.FullPath, $_.TimeGenerated
   
}

 

Which depends on the correct identification of the order in which events are issued.  That seemed like too much manual intervention. It was too late last night to solve so I had another look today and came up with this

001
002
Get-Event -SourceIdentifier "File System Changed" | Group TimeGenerated | where {$_.Count-eq 2} | 
foreach {$time = $_.Name; Get-Event | where {$_.TimeGenerated.ToString() -eq $time}| select -First 1}

 

use get-event with the correct source identifier. We then group on timegenerated.  File Changes will generate two change records per event so we select where the count is 2.  Pass those into a foreach and retrieve the events matching that time. We select the first one of each pair to only access a single record. One neat line of PowerShell does it all.

Published Mon, Nov 9 2009 20:04 by RichardSiddaway

Leave a Comment

(required) 
(required) 
(optional)
(required)