I wrote code with the WPF window to synchronize files between two folders. After clicking the Run button, the code will run and monitor changes in folder f1. If a change is detected, it will execute the condition with f2. However, after I pressed the run button, nothing happened, WPF froze and had to be turned off. Please tell me what I did wrong and how I should fix it? Sincerely thank you!
function StartWatching {
param (
[string]$F1s,
[string]$F2s,
[bool]$Recycles,
[bool]$Backups,
[string]$BackupPaths,
[int]$Time
)
if (($Recycles -eq $true) -or ($Backups -eq $true)) {
Check-Folders -F1 $F1s -F2 $F2s -Recycle $Recycles -Backup $Backups -BackupPath $BackupPaths
}
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $F1s
$watcher.IncludeSubdirectories = $true
$watcher.NotifyFilter = [System.IO.NotifyFilters]'FileName, DirectoryName, LastWrite, Size'
$action = {
param($sourceEventArgs)
if (($Recycles -eq $true) -or ($Backups -eq $true)) {
Check-Folders -F1 $F1s -F2 $F2s -Recycle $Recycles -Backup $Backups -BackupPath $BackupPaths
}
robocopy $F1s $F2s /MIR /COPYALL /Z /R:5 /W:10
}
$onChanged = Register-ObjectEvent -InputObject $watcher -EventName Changed -Action $action
$onCreated = Register-ObjectEvent -InputObject $watcher -EventName Created -Action $action
$onDeleted = Register-ObjectEvent -InputObject $watcher -EventName Deleted -Action $action
$onRenamed = Register-ObjectEvent -InputObject $watcher -EventName Renamed -Action $action
$watcher.EnableRaisingEvents = $true
while ($true) {
Start-Sleep -Seconds $Time
}
}
$watcher = $null
$onChanged = $null
$onCreated = $null
$onDeleted = $null
$onRenamed = $null
...
$run.Add_Click({
StartWatching -F1s $folder1.Text -F2s $folder2.Text -Recycles $Recycle.IsChecked -Backups $Backup.IsChecked -BackupPaths $BackupDir.Text -Time $rptime.Text
})
$window.ShowDialog() | Out-Null
if ($watcher -ne $null) {
$watcher.EnableRaisingEvents = $false
Unregister-Event -SubscriptionId $onChanged.Id
Unregister-Event -SubscriptionId $onCreated.Id
Unregister-Event -SubscriptionId $onDeleted.Id
Unregister-Event -SubscriptionId $onRenamed.Id
$watcher.Dispose()
}