Created
April 22, 2020 02:08
-
-
Save SeriaWei/7b7cf695d80b15a23d93435715538e9b to your computer and use it in GitHub Desktop.
Powershell watch file change
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$watchPath = Read-Host "Please input a path to watch" | |
### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO | |
$filewatcher = New-Object System.IO.FileSystemWatcher | |
#Mention the folder to monitor | |
$filewatcher.Path = $watchPath | |
$filewatcher.Filter = "*.*" | |
#include subdirectories $true/$false | |
$filewatcher.IncludeSubdirectories = $true | |
$filewatcher.EnableRaisingEvents = $true | |
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED | |
$writeaction = { $path = $Event.SourceEventArgs.FullPath | |
$changeType = $Event.SourceEventArgs.ChangeType | |
$logline = "$(Get-Date), $changeType, $path" | |
Write-Host $logline | |
Add-content "FileChange.log" -value $logline | |
} | |
### 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 | |
Write-Host "Watching [$watchPath] ..." | |
while ($true) { Start-Sleep 1 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment