Powershell 和 System.IO.FileSystemWatcher

Powershell and System.IO.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 ??
Unregister-Event $created.Id

这将注销活动。您可能希望将其添加到 $action.

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

This 也可能有帮助。

运行 作为对订阅事件的操作的脚本块可以访问 $Args、$Event、$EventArgs 和 $EventSubscriber automatic variables

只需将 Unregister-Event 命令添加到脚本块的末尾,如下所示:

### 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  
            Unregister-Event -SubscriptionId $EventSubscriber.SubscriptionId            
          }    

这是只执行一次操作然后自行清理的事件的模式。

很难有效地探索这些自动变量,因为它们在作业的范围内,但是您可以在草拟代码时通过将它们分配给全局变量来使用它们。您可能还会从 Wait-Debugger 和 Debug-Runspace 中获得一些乐趣。在 $EventSubscriber 变量的情况下,它 returns 如果您 运行 Get-EventSubscriber (已经创建了一个订阅),您将获得确切的对象。这就是我找到 SubscriptionId 属性.

的方式

如果你想stop/unregister所有注册的事件你可以调用

Get-EventSubscriber|Unregister-Event