設為首頁收藏本站

艾歐踢論壇

 找回密碼
 立即註冊

QQ登錄

只需一步,快速開始

搜索
熱搜: 活動 交友 discuz
查看: 170|回復: 0
打印 上一主題 下一主題

monitor a folder and trigger a command-line action when a file is created ?

[複製鏈接]
跳轉到指定樓層
樓主
發表於 2023-12-16 04:17:11 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
At work we use Powershell to monitor folders.
It can be used since Windows Vista (.NET and PowerShell is preinstalled) without any additional tools.

This script monitors a certain folder and writes a logfile. You can replace the action and do whatever you want e.g call an external tool

Example log file
11/23/2014 19:22:04, Created, D:\source\New Text Document.txt
11/23/2014 19:22:09, Changed, D:\source\New Text Document.txt
11/23/2014 19:22:09, Changed, D:\source\New Text Document.txt
11/23/2014 19:22:14, Deleted, D:\source\New Text Document.txt
StartMonitoring.ps1
### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "D:\source"
    $watcher.Filter = "*.*"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true  

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { $path = $Event.SourceEventArgs.FullPath
                $changeType = $Event.SourceEventArgs.ChangeType
                $logline = "$(Get-Date), $changeType, $path"
                Add-content "D:\log.txt" -value $logline
              }   
### DECIDE WHICH EVENTS SHOULD BE WATCHED
    Register-ObjectEvent $watcher "Created" -Action $action
    Register-ObjectEvent $watcher "Changed" -Action $action
    Register-ObjectEvent $watcher "Deleted" -Action $action
    Register-ObjectEvent $watcher "Renamed" -Action $action
    while ($true) {sleep 5}
How to use
  • Create a new text file
  • Copy & paste the above code
  • Change the following settings to your own needs:
  • folder to monitor: $watcher.Path = "D:\source"
  • file filter to include only certain file types: $watcher.Filter = "*.*"
  • include subdirectories yes/no: $watcher.IncludeSubdirectories = $true
  • Save and rename it to StartMonitoring.ps1
  • Start monitoring by Right click » Execute with PowerShell
To stop monitoring, it's enough to close your PowerShell window
分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏 轉播轉播 分享分享 分享淘帖
回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|Archiver|手機版|艾歐踢創新工坊    

GMT+8, 2024-5-16 14:24 , Processed in 0.190621 second(s), 18 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表