Powershell IO.FileSystemWatcher过滤器

时间:2018-12-20 16:18:09

标签: powershell filesystemwatcher

我创建了一个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一起工作。任何建议表示赞赏。

谢谢

2 个答案:

答案 0 :(得分:2)

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

  

不支持使用多个过滤器,例如"*.txt|*.doc"

听起来您必须:

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

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

答案 1 :(得分:1)

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
        }
    }
}
相关问题