Skip to content

Instantly share code, notes, and snippets.

@jmreicha
Last active July 1, 2019 13:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jmreicha/82f25e3385c8d6515360a1f3d3bce333 to your computer and use it in GitHub Desktop.
Save jmreicha/82f25e3385c8d6515360a1f3d3bce333 to your computer and use it in GitHub Desktop.
File watcher scripts
# 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
@dibu17
Copy link

dibu17 commented Jul 1, 2019

How will capture user details(AD) with same script?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment