使用 Powershell 監控目錄/檔案變更

powershell 除了免編譯就能直接執行的強大好處之外,還能使用 c# 或是自定義的 dll 裡的物件使用,而這邊要介紹的是如何使用 powershell 使用 c# 的 FileSystemWatcher 物件,以達到監控檔案目錄的

FileSystemWatcher 物件的介紹,在此就不多說,可以直接參考 ms document 上的介紹

然而在 powershell 上使用方式有一點不同,但屬性與方法上是一樣的東西

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
   $filewatcher = New-Object System.IO.FileSystemWatcher
   #Montion the folder to monitor
   $filewatcher.Path = "E:\Site\"
   $filewatcher.Filter = "*.*"
   #include subdirectories $true/$false
   $filewatcher.IncludeSubdirectories = $true
   $filewatcher.EnableRaisingEvents = $false  
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
   $writeaction = { $path = $Event.SourceEventArgs.FullPath
               $changeType = $Event.SourceEventArgs.ChangeType
               $logline = "$(Get-Date), $changeType, $path"
               Add-content "E:\Log\FileWatcher_log.txt" -value $logline
               Add-content "E:\Log\FileWatcher_log.txt"" -value ($Event | ConvertTo-Json -Compress)    
             }    
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
#The Register-ObjectEvent cmdlet subscribes to events that are generated by .NET objects on the local computer or on a remote computer.
#When the subscribed event is raised, it is added to the event queue in your session. To get events in the event queue, use the Get-Event cmdlet.
   Register-ObjectEvent $filewatcher "Created" -Action $writeaction
   Register-ObjectEvent $filewatcher "Changed" -Action $writeaction
   Register-ObjectEvent $filewatcher "Deleted" -Action $writeaction
   Register-ObjectEvent $filewatcher "Renamed" -Action $writeaction

 

偵錯

若要挑缺點的話,相較 vs IDE 工具上,在 powershell 上 debug 的確不是那麼方便

僅管如此,windows 還是有出了 windows powhsell ISE 的工具提供給我們偵錯

但在這個事件處理上,powerhsell ISE 的偵錯工具卻是無法進入的

不過沒關係,powerhsell 偵錯還有另一個方式,直接把內容寫出來,以下則是直接把 $Event 序列化成 json 格式

這樣一來我們就知道 $Event 裡有什麼屬性了

Add-content "E:\Log\FileWatcher_log.txt"" -value ($Event | ConvertTo-Json -Compress)    

下一篇則會介紹我們怎麼把 powhsell 的 script 掛到 windows service 去

參考資料
https://docs.microsoft.com/zh-tw/dotnet/api/system.io.filesystemwatcher?view=net-5.0
https://dotnet-helpers.com/powershell/how-to-monitor-a-folder-changes-using-powershell/
https://docs.microsoft.com/zh-tw/powershell/scripting/windows-powershell/ise/how-to-debug-scripts-in-windows-powershell-ise?view=powershell-7.1
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json?view=powershell-7.1