Powershell:FileSystemWatcher过滤器选项-不起作用。

时间:2018-10-11 12:54:30

标签: powershell filter

我要注意文件名,例如“今天的日期,然后是6位数字,然后是_ABC_XYZ.csv”。例如如果今天的日期是20181011,则文件的名称应为:20181011123456_ABC_XYZ.csv。下面是我的代码:

$DateStr = $Date.ToString("yyyyMMdd")

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "E:\\Sid\\source"
    $watcher.Filter = $DateStr + "\d\d\d\d\d\d*_Recon_ForeignExchange.csv"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true  

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { $path = $Event.SourceEventArgs.FullPath
                $changeType = $Event.SourceEventArgs.ChangeType
                $logline = "$(Get-Date), $changeType, $path"
                Add-content "D:\log.txt" -value $logline            
              }    
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
    Register-ObjectEvent $watcher "Created" -Action $action
    Register-ObjectEvent $watcher "Changed" -Action $action
    Register-ObjectEvent $watcher "Deleted" -Action $action
    Register-ObjectEvent $watcher "Renamed" -Action $action
    while ($true) {sleep 5} 

我的查询:

  1. 似乎$ watcher.filter无法正常工作,因为它正在接收除过滤器中指定文件以外的文件。

  2. 我也想一次查看2个文件夹,因为该文件可以放在任何文件夹中。我该如何实现?

1 个答案:

答案 0 :(得分:2)

正如@Theo所指出的,Filter属性不支持正则表达式。仅允许使用路径通配符。

您将不得不在过滤器中使用一个更简单的通配符:

# rough wildcard filter
$watcher.Filter = "*_Recon_ForeignExchange.csv"

..然后在处理程序中执行更具体的(正则表达式)检查:

$action = {   
  $path = $Event.SourceEventArgs.FullPath
  # check if the file name has the desired format
  if ((Split-Path $path -Leaf) -match ($DateStr + "\d\d\d\d\d\d*_Recon_ForeignExchange.csv"))
    $changeType = $Event.SourceEventArgs.ChangeType
    $logline = "$(Get-Date), $changeType, $path"
    Add-content "D:\log.txt" -value $logline
  }    
}

对于其他目录,@ vrdse已经指出您将需要第二个监视程序。