| Richard's profileRichard Siddaway's BlogPhotosBlogLists | Help |
|
November 09 Watching the file systemWe saw how to watch for WMI events http://msmvps.com/blogs/richardsiddaway/archive/2009/11/07/powershell-wmi-events.aspx. In this post we will look at watching the file system. This time we will use the .NET System.IO.FileSystemWatcher object which means we use Register-ObjectEvent instead of Register-WmiEvent.
We can start by defining the folder we want to watch and which files. In this case I want to watch all files. We can restrict it to certain files e.g. $filter = “*.txt” Wildcards work in the normal way for this filter. We could even restrict to a single file. The events we are interested in are defined. After creating a System.IO.FileSystemWatcher object using the folder and filter in the construction we set the IncludeSubDirectories property so we are watching the whole path. Finally we need to register an event for each event we are interested in. Notice how the SourceIdentifier changes to identify the particular event. We can see the Eventsubscribers we have created. PS> Get-EventSubscriber | Select SubscriptionId, EventName, SourceIdentifier | ft -a SubscriptionId EventName SourceIdentifier We now need to perform some actions on the files – create, change, rename, delete that we are monitoring PS> Get-Event | group SourceIdentifier Count Name Group If we look at this in more detail PS> Get-Event | select EventIdentifier, SourceIdentifier, TimeGenerated EventIdentifier SourceIdentifier TimeGenerated
Note that we get pairs of events – the second event of the pair is always a change event. If we just want to see the changes (and remove duplicates). Just be careful on this and check whether its the odd or even record you need if running multiple registered events.
We can use Get-Event to pull the change events from the queue. The modulo arithmetic on the EventIdentifier ensures that we only get the first change record. We can then dump the file path and time of change. In a similar way we can interrogate the other events
These four could be combined into a single script if required. Combined with the process tracing we did previously we can now track what programs are started on a system and what files are accessed. Comments (1)
TrackbacksThe trackback URL for this entry is: http://richardsiddaway.spaces.live.com/blog/cns!43CFA46A74CF3E96!2601.trak Weblogs that reference this entry
|
|
|