I am trying to build a FileWatcher program in Windows PowerShell. I have 4 locations which I need to monitor. In those 4 locations I already have hundreds of files.
I have a specific format for the file which I receive; e.g. the file name begins with yesterday's date, i.e. if today's date is 2018-11-19 then the file which I need to monitor starts with 20181118[5 digits]_ABC_XYZ.csv
(I think that I would need to use regular expressions here).
After I receive the file I need to check whether the file is in that particular format and if it is then I need to copy the file at a specified place. The file may come at any time.
Following is the program code which I could test till now:
$Date = (Get-Date).AddDays(-1)
$DateStr = $Date.ToString("yyyyMMdd")
### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\source"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = { $path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$Name = $Event.SourceEventArgs.Name
$Extension = $Event.SourceEventArgs.Name.extension
$logline = "$(Get-Date), $changeType, $path, $Name, $Extension"
Add-content "D:\log.txt" -value $logline
}
### DECIDE WHICH EVENTS SHOULD BE WATCHED
Register-ObjectEvent $watcher "Created" -Action $action
Register-ObjectEvent $watcher "Changed" -Action $action
while ($true) {sleep 5}
I understand that I need to write the code in $action block to check for the format of the file I receive and is the file is in the proper format then I need to copy the file to another location.
Please kindly guide me in checking for the format of the file in the $action
block and further copying the file. Also how do I monitor 4 locations? Do I give 4 paths in $watcher.Path
separated by commas?