4

I have created a IO.filesystemwatcher to monitor a folder and take an action when certain file types are written to the location. I am looking for file types .jpg and .tmp. I have named the filter as a variable, and the filter works when including one file type, but not two types.

Code below functions correctly:

$filter = '*.jpg'
New-Object IO.FileSystemWatcher $Folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

Code below functions correctly:

$filter = '*.tmp'
New-Object IO.FileSystemWatcher $Folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

Code below DOES NOT function:

$filter = '*.tmp','*jpg'
New-Object IO.FileSystemWatcher $Folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

I have also tried $filter = '*.tmp' -or '*jpg'

I am sure there's a different way to do this to make it work, but I am not very good at working with IO.filesystemwatcher. Any recommendations are appreciated.

Thanks

2 Answers 2

4

The .Filter property is [string]-typed and supports only a single wildcard expressions; from the docs:

Use of multiple filters such as "*.txt|*.doc" is not supported.

It sounds like you'll have to:

  • either: watch for changes to all files, by setting .Filter to '' (the empty string), and then perform your own filtering inside your event handler.

  • or: set up a separate watcher instance for each filter (wildcard pattern). Thanks, mhhollomon.

Sign up to request clarification or add additional context in comments.

Comments

1

Filter is a single string. You can inspect the raised event to find the full path and compare it to your filters:

$Script:filter = @('*.txt','*jpg','*.csv')
If($FileWatcher){$FileWatcher.Dispose();$FileWatcher = $null}
$FileWatcher = New-Object System.IO.FileSystemWatcher -Property @{
    IncludeSubdirectories = $true;
    NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
    Path =  'C:\Users\proxb\Desktop\DropBox\'
}
Register-ObjectEvent -InputObject $FileWatcher  -EventName Created -Action {
    Write-Host "File: $($event.SourceEventArgs.FullPath) was $($event.SourceEventArgs.ChangeType) at $($event.TimeGenerated) "
    $Script:filter | ForEach{
        If($event.SourceEventArgs.FullPath -like $_){
            Write-Host "$($event.SourceEventArgs.FullPath) matched $_" 
            #Do something here
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.