Improve Existing PowerShell to Monitor Multiple Folders
- Status: Closed
- Prize: $25
- Entries Received: 1
- Winner: num13
Contest Brief
I have the following script which monitors a 'source' folder. When any data enters the source folder, it is moved to a 'destination' folder. This is working well with 1 source and 1 destination folder. My issue is that I need to monitor 6 source folders and 3 receive folders. I have 3 disconnected networks. They are to remain separate from each other for security reasons. The idea is to have a data diode of sorts between the networks.
So if the networks are A, B and C.
I need to monitor 6 source folders.
A to B, A to C, B to A, B to C, C to A, C to B.
and 3 destination folders
A Receive, B Receive and C Receive.
I'm looking for direction on how best to do this.
Here's my current script:
-----------------------------------------------------------------------------------------------------------
# The paths for the source and destination folders
$global:source = "D:\Source"
$global:dest = "D:\Destination"
# Path to the log file.
$global:log_file = "D:\log.txt"
if (!(Test-Path $global:source)) {
Write-Host "Source folder doesn't exist!"
Exit
}
if (!(Test-Path $global:dest)) {
Write-Host "Destination folder doesn't exist!"
Exit
}
if (Test-Path function:unwatch) {
unwatch
}
$filter = '*.*' # You can enter a wildcard filter here.
$fsw = New-Object IO.FileSystemWatcher $source, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'DirectoryName, FileName, LastWrite'}
$action = {
$name = $Event.SourceEventArgs.Name
$source_path = Join-Path $global:source $name
$dest_path = Join-Path $global:dest $name
$dir = Split-Path -Parent $dest_path
$time = Get-Date -Format "[yyyy/MM/dd HH:mm]"
if (!(Test-Path $dir)) {
mkdir $dir
}
Move-Item -Force -Path $source_path -Destination $dest_path
Write-Output "$time Moved $name to $dest_path" >> "$global:log_file"
}
$a = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action $action
$a = Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action $action
$a = Register-ObjectEvent $fsw Renamed -SourceIdentifier FileRenamed -Action $action
function global:unwatch {
Unregister-Event FileCreated
Unregister-Event FileChanged
remove-item function:unwatch
Write-Host "Stopped."
}
Write-Host "Watching for changes!"
Write-Host "Type 'unwatch' and press enter to stop." -ForegroundColor green
--------------------------------------------------------------------------------------------------------------------
Thanks!
Recommended Skills
Employer Feedback
“Sergey did good work and was quick to make changes that I needed. Would hire again.”
smith2487, Canada.
Top entries from this contest
-
num13 Russian Federation
Public Clarification Board
How to get started with contests
-
Post Your Contest Quick and easy
-
Get Tons of Entries From around the world
-
Award the best entry Download the files - Easy!