Powershell和System.IO.FileSystemWatcher [英] Powershell and System.IO.FileSystemWatcher

查看:276
本文介绍了Powershell和System.IO.FileSystemWatcher的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to PowerShell and I am trying to use the System.IO.FileSystemWatcher to monitor the presence of a file in a specified folder. However, as soon as the file is detected I want to stop monitoring this folder immediately and stop the FileSystemWatcher. The plan is to incorporate the PowerShell script into a SQL Agent to enable users to restore their own databases. Basically I need to know the command to stop FileSystemWatcher from monitoring as soon as one file is found. Here is the script so far.

### 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 will unregister the event. You will probably want to add this to the $action.

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

Do note that if there are events in the queue they will still be fired.

可能也有帮助.

这篇关于Powershell和System.IO.FileSystemWatcher的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆