我使用FileSystemWatcher创建了一个powershell脚本。此脚本会监视网络驱动器,如果有任何事件运行robocopy。
例如: 每次创建,更改或删除文件时,都会执行robocopy。
但是,FileSystemWatcher没有检测到"更改"事件,但只有"创建"和"删除"事件
当我通过观察本地目录测试FileSystemWatcher时,更改,创建和删除事件正常工作。
这是代码:
$folderBack = '\\network_drive\' # Enter the root path you want to monitor.
$filterBack = '*.*' # You can enter a wildcard filter here.
$fswBack = New-Object IO.FileSystemWatcher $folderBack, $filterBack -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
Register-ObjectEvent $fswBack Changed -SourceIdentifier FileChangedBack -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Start-Sleep 5
robocopy \\network_drive\ G:\local\ /E /MIR /DST /FFT /XO /XJ /MT:8 /R:3 /W:10 /Z /NP /NDL /XF ~* *.TMP /LOG:robocopy.log
Write-Host "The file '$name' was $changeType at $timeStamp" -fore white
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}
Register-ObjectEvent $fswBack Created -SourceIdentifier FileCreatedBack -Action {
$nameBack = $EventBack.SourceEventArgs.Name
$changeTypeBack = $EventBack.SourceEventArgs.ChangeType
$timeStampBack = $EventBack.TimeGenerated
robocopy robocopy \\network_drive\ G:\local\ /E /MIR /DST /FFT /XO /XJ /MT:8 /R:3 /W:10 /Z /NP /NDL /XF ~* *.TMP /LOG:robocopy.log
Write-Host "The file '$nameBack' was $changeTypeBack at $timeStampBack" -fore green
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$nameBack' was $changeTypeBack at $timeStampBack"}
Register-ObjectEvent $fswBack Deleted -SourceIdentifier FileDeletedBack -Action {
$nameBack = $Event.SourceEventArgs.Name
$changeTypeBack = $Event.SourceEventArgs.ChangeType
$timeStampBack = $Event.TimeGenerated
robocopy robocopy \\network_drive\ G:\local\ /MIR /DST /FFT /XO /XJ /MT:8 /R:3 /W:10 /Z /NP /NDL /XF ~* *.TMP /LOG:robocopy.log
Write-Host "The file '$nameBack' was $changeTypeBack at $timeStampBack" -fore red
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$nameBack' was $changeTypeBack at $timeStampBack"}
感谢。