Powershell 和 System.IO.FileSystemWatcher

Lee*_*ker 5 powershell filesystemwatcher

我是 PowerShell 的新手,我正在尝试使用 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 ??
Run Code Online (Sandbox Code Playgroud)

It-*_*t-Z 5

Unregister-Event $created.Id
Run Code Online (Sandbox Code Playgroud)

这将取消注册该事件。您可能希望将其添加到 $action 中。

请注意,如果队列中有事件,它们仍然会被解雇。

也可能有帮助。