简体   繁体   中英

Powershell IO.FileSystemWatcher filters

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

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 .

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
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM