Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Would like to watch directory for changes

$
0
0

Hey everyone. I'd like to watch a directory for changes so that I can save the files in there to another location to back them up each time.

So what I'm writing is a script that will start a process, then listen for change events to a directory that the process writes to. When it changes, I'm going to backup the changes to another location.

My problem right now is that if I listen to 'childFolder' I will get an event if a file is created but not if a directory is created.

But according to the MSDN here http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher_events(v=vs.110).aspx it shows that it should fire when a directory is created.

As a test, I used Start-Process to start cmd.exe, and then started watching a folder, then from within the opened cmd.exe i created a file in the watched folder, and i get the printout for the created event, but if I created a directory in the same folder, I don't get the printout for the folder being created. Yet if I delete both a file AND/OR directory from childFolder I DO get the changed event. 

So the only thing I'm not getting that I feel I should get, is an event for when a directory is created inside of childFolder

$folder = 'C:\parentFolder\childFolder'

$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'LastWrite'}

#listen for the file changed event
Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    Write-Host "The file '$name' was $changeType at $timeStamp" -fore white
}

#listen for the file created event
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    Write-Host "The file '$name' was $changeType at $timeStamp" -fore green


Viewing all articles
Browse latest Browse all 6937

Trending Articles