Powershell 和 System.IO.FileSystemWatcher

标签 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 ??

最佳答案

Unregister-Event $created.Id

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

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

This也可能有帮助。

关于Powershell 和 System.IO.FileSystemWatcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31795933/

相关文章:

c# - 重命名文件Powershell看不到

PowerShell 自动加载自定义模块 "preparing modules"消息卡住

c# - 无法使用 powershell 远程启动 WCFapplication (System.ServiceModel)

powershell - 使用 PowerShell 在更改时复制文件

powershell - 在 powershell if 语句中使用类似变量

c# - 添加带有子目录的文件夹时的 FileSystemWatcher 事件

c# - FileSystemWatcher Changed 事件不会针对内存映射文件触发

.net - 使用 FileSystemWatcher 确定 FTP 上传的文件何时准备好进行处理

c# - 使用FileSystemWatcher检测xml文件,使用Linq读取xml文件提示结果错误 "Root Element is Missing"

windows - 如何找出谁在运行 runas 应用程序?