Powershell IO.FileSystemWatcher 过滤器

Powershell IO.FileSystemWatcher filters

我创建了一个 IO.filesystemwatcher 来监视文件夹并在将某些文件类型写入该位置时采取措施。我正在寻找文件类型 .jpg.tmp。我已将过滤器命名为变量,并且过滤器在包含一种文件类型而不是两种类型时起作用。

以下代码运行正常:

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

以下代码运行正常:

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

下面的代码不起作用:

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

我也试过了$filter = '*.tmp' -or '*jpg'

我确信有不同的方法可以做到这一点,但我不太擅长使用 IO.filesystemwatcher。任何建议表示赞赏。

谢谢

.Filter property[string]类型的,只支持单个通配符表达式;来自文档:

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

听起来你必须:

  • 或者:通过将 .Filter 设置为 ''(空字符串)来监视对 所有 文件的更改,然后在您的事件处理程序中执行您自己的过滤。

  • 或者:为每个过滤器设置一个单独的观察器实例(通配符模式)。 谢谢,mhhollomon

Filter is a single string. 您可以检查引发的事件以找到完整路径并将其与您的过滤器进行比较:

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