I am using a $watcher (FileSystemWatcher) to trigger an $action, when a docx-File is being created or changed in a directory:

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\ExportedDocuments"
$watcher.Filter = "*.docx*"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true  
$action = [scriptblock]::Create('
### here is my complete script
Register-ObjectEvent $watcher "Created" -Action $action
Register-ObjectEvent $watcher "Changed" -Action $action
while ($true) {}

Unfortunately, in the directory where the $watcher (FileSystemWatcher) is looking through, sometimes temporary files are created:

01/23/2019 07:53:52, Created, C:\ExportedDocuments\~$FFFFFFFF.docx

Which means that temporary files are also detected by the $watcher (FileSystemWatcher) and force the $action to run.

Is there a way, to exclude these temporary files from the $watcher?


According to the documentation you can't have multiple filters :

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

However you can put the filter in your $action. For example :

$action = { $fileName = Split-Path $Event.SourceEventArgs.FullPath -leaf

            if ($fileName -like '~$*') { $logline = "$(Get-Date), $fileName, 'TEMP'"}
            else { $logline = "$(Get-Date), $fileName, 'NOT TEMP'" }

            Add-content "D:\test\log.txt" -value $logline

Produces output like this :

01/23/2019 11:37:37, ~$f.docx, 'TEMP'
01/23/2019 11:37:37, ~$f.docx, 'TEMP'
01/23/2019 11:38:29, New Microsoft Word Document.docx, 'NOT TEMP'

So to simply exclude temporary files based on your '~$' pattern you could make $action like :

$action = { $fileName = Split-Path $Event.SourceEventArgs.FullPath -leaf
            if (-not ($fileName -like '~$*')) {
              # Do whatever
| improve this answer | |

Unfortunately not. Your handler will have to determine which file is a temp file and ignore it. In case of MSWord temp files: name starting with a tilde (~) and/or hidden attribute

| improve this answer | |
  • Thanks for your answer. Do you have a code sample for me? – SteffPoint Jan 23 '19 at 10:48
  • Not now, but I saw @lx07 has provided a code sample in another answer – Gert Jan Kraaijeveld Jan 23 '19 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.