Powershell和System.IO.FileSystemWatcher

我是Power
Shell的新手,我正在尝试使用System.IO.FileSystemWatcher来监视指定文件夹中是否存在文件.但是,一旦检测到文件,我想立即停止监视此文件夹并停止FileSystemWatcher.计划是将PowerShell脚本合并到SQL代理中,以使用户能够还原自己的数据库.基本上我需要知道一旦找到一个文件就停止监视FileSystemWatcher的命令.这是迄今为止的脚本.

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "C:\TriggerBatch"
    $watcher.Filter = "*.*"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true  

### DEFINE ACTIONS AFTER A EVENT IS DETECTED
    $action = { $path = $Event.SourceEventArgs.FullPath
                $changeType = $Event.SourceEventArgs.ChangeType
                $logline = "$(Get-Date), $changeType, $path"
                Add-content "C:\log2.txt" -value $logline              
              }    

### DECIDE WHICH EVENTS SHOULD BE WATCHED + SET CHECK FREQUENCY  
    $created = Register-ObjectEvent $watcher Created -Action $action

while ($true) {sleep 1} 

## Unregister-Event Created ??
##Stop-ScheduledTask ??

最佳答案

Unregister-Event $created.Id

这将取消注册该事件.您可能希望将此添加到$action.

请注意,如果队列中有事件,它们仍将被触发.

This可能也有帮助.

点赞