Skip to content

Instantly share code, notes, and snippets.

@royashbrook
Last active February 5, 2019 15:49
Show Gist options
  • Save royashbrook/bf8419a82dbc6de5c4a7b160256d446b to your computer and use it in GitHub Desktop.
Save royashbrook/bf8419a82dbc6de5c4a7b160256d446b to your computer and use it in GitHub Desktop.
# references:
# https://community.spiceworks.com/topic/380201-using-powershell-to-check-for-new-files-in-a-directory
# https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/register-objectevent
# https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher
# you can change $p to whatever path you want, you can also add file filters, and add more events
# i am monitoring a folder for all create/delete events and color coding output
$p = $pwd.path
$w = New-Object System.IO.FileSystemWatcher $p
$w.IncludeSubdirectories = $true
function a($e,$c){($e.TimeGenerated,$e.SourceEventArgs.ChangeType,$e.SourceEventArgs.FullPath) -join "," | Write-Host -f $c}
Register-ObjectEvent $w -EventName created -Action { a $event "green" }
Register-ObjectEvent $w -EventName deleted -Action { a $event "red" }
# if you'd like to simulate create/change/rename/delete, here's a simple loop to do so.
# just make sure you are in the same path as $p above.
while ($true){
dir *.* > .\a.txt
dir *.txt >> .\a.txt
ren a.txt b.txt
del b.txt
sleep 5
}
# to remove all of the watchers, run below. This is assuming you don't have any other
# event subscriptions you want to keep live. If so, you probably already know what to do. =)
Get-EventSubscriber -Force | Unregister-Event -Force
#watch for a single file creation event
function w1($p){
$a = {
$msg = ($Event.TimeGenerated,$Event.SourceEventArgs.ChangeType,$Event.SourceEventArgs.FullPath) -join ","
$m = @{
To = "email to text for your provider"
From = "[email protected]"
Smtpserver = "yoursmtpserver"
Port = 25
}
Send-MailMessage @m -Subject "w1 alert - $(get-date)" -Body $msg
Unregister-Event -SubscriptionId $EventSubscriber.SubscriptionId
"Email Sent. Halted Monitoring" | write-host -f cyan
}
$w = New-Object System.IO.FileSystemWatcher $p
$w.IncludeSubdirectories = $true
Register-ObjectEvent $w -EventName created -Action $a
}
w1 "\\server\share"
$p = "path to folder"
$w = New-Object System.IO.FileSystemWatcher $p
$w.IncludeSubdirectories = $true
function a($e,$c){
$msg = ($e.TimeGenerated,$e.SourceEventArgs.ChangeType,$e.SourceEventArgs.FullPath) -join ","
$msg | Write-Host -f $c
}
Register-ObjectEvent $w -EventName created -Action { a $event "green" }
Register-ObjectEvent $w -EventName deleted -Action { a $event "red" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment