-
-
Save jmreicha/82f25e3385c8d6515360a1f3d3bce333 to your computer and use it in GitHub Desktop.
File watcher scripts
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
# CLI params for starting and stoppping the watcher | |
param ( | |
[switch]$start = $false, | |
[switch]$stop = $false | |
) | |
Function Register-Watcher { | |
# Folder to watch | |
param ($watchdir) | |
$watchdir = "C:\Users\$env:USERNAME\Documents" # Root path to monitor | |
$logfile = "c:\Users\$env:USERNAME\logfile.txt" | |
# Filter all files and subdirectories | |
$filter = "*.*" | |
$watcher = New-Object IO.FileSystemWatcher $watchdir, $filter -Property @{ | |
IncludeSubdirectories = $true | |
EnableRaisingEvents = $true | |
} | |
# Create the log file if it doesn't exist | |
if (!(Test-Path "$logfile")) { | |
New-Item -path "$logfile" -type file | Out-Null | |
} | |
# Define the FS watching behvior | |
$action = { | |
$path = $Event.SourceEventArgs.FullPath | |
$name = $Event.SourceEventArgs.Name | |
$changeType = $Event.SourceEventArgs.ChangeType | |
$timeStamp = $Event.TimeGenerated | |
#$console_message = "The file '$name' was '$changeType' at '$timeStamp'" | |
#Write-Host $console_message | |
$log_message = "$name, $changeType, $timeStamp" | |
Out-File "C:\Users\$env:USERNAME\logfile.txt" -Append -InputObject $log_message | |
} | |
# Register the FS watcher | |
Register-ObjectEvent $watcher Created -SourceIdentifier Created -Action $action | |
Register-ObjectEvent $watcher Changed -SourceIdentifier Changed -Action $action | |
Register-ObjectEvent $watcher Deleted -SourceIdentifier Deleted -Action $action | |
Register-ObjectEvent $watcher Renamed -SourceIdentifier Renamed -Action $action | |
} | |
# Unregister the FS watcher | |
Function Unregister-Watcher() { | |
Unregister-Event Created | |
Unregister-Event Changed | |
Unregister-Event Deleted | |
Unregister-Event Renamed | |
} | |
Function Main() { | |
# Start the watcher | |
if ($start) { | |
Write-Host "Starting FS watcher" -fore green | |
Register-Watcher $watchdir | |
} | |
# Stop the watcher | |
elseif ($stop) { | |
Write-Host "Stopping FS watcher" -fore red | |
Unregister-Watcher | |
} | |
# Otherwise error | |
else { | |
Write-Host "Invalid arguments" | |
Write-Host $args.Length | |
} | |
} | |
# Script entrypoint | |
Main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How will capture user details(AD) with same script?