Skip to content

Instantly share code, notes, and snippets.

@gitfvb
Created December 19, 2018 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gitfvb/b90299d83a9a0162a503610aef8e4393 to your computer and use it in GitHub Desktop.
Save gitfvb/b90299d83a9a0162a503610aef8e4393 to your computer and use it in GitHub Desktop.
A "watchdog" to monitor a specific folder for an event like "created, changed...". To get this automatically running it has to be included in the windows tasks.
We can make this file beautiful and searchable if this error is corrected: No commas found in this CSV file in line 0.
CustId Straße PLZ Ort
123 D-Str. 5 52080 Aachen
456 Am Keller 2 61080 Bad Vilbel
789 Kaiserstraße 35 60329 Frankfurt am Main
# create filewatcher object
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\Users\Florian\Desktop\20181216\filewatcher"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
$watcher.Filter = "*.csv"
# show possible events
$SupportedEvents = $watcher | Get-Member | where {$_.membertype -eq 'Event' }
$SupportedEvents
# This defines what happens when the event "Created" happens.
Register-ObjectEvent $watcher -EventName Created -Action {
# This is the triggered event
$e = $event
( $e.TimeGenerated,$e.SourceEventArgs.ChangeType,$e.SourceEventArgs.FullPath ) -join ", " | Write-Host
# Definition of im- and export data
$importfile = Get-Item -Path $e.SourceEventArgs.FullPath
$exportfile = "$( $importfile.Directory.Parent.FullName )\export.csv"
Remove-Item -Path $exportfile -Recurse
# load and export data
$csv = Import-Csv -Path $importfile.FullName -Delimiter "`t" -Encoding UTF8
Write-Host $exportfile
$csv | Select custId, PLZ | export-csv -Path $exportfile -Encoding UTF8 -Delimiter ";" -NoTypeInformation
}
#Register-ObjectEvent $w -EventName Deleted -Action { a $event "red" }
# This loop keeps the script running
while ($true){
Start-Sleep -Seconds 10
}
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment