我有一个基于New-Object System.IO.FileSystemWatcher的脚本,它在我的主文件服务器上查看新文件的文件夹,并运行一个外部应用程序,但现在我正在寻求扩展使用New-Object System.IO.FileSystemWatcher,用于监视一组多个服务器(从.csv输入)。
我已经得到了以下代码,只要检测到事件,但是当检测到新文件时,它会多次生成新文件的警报。知道我怎么能得到它只是生成一个警报?我在想这是我的循环结构如何?
任何帮助表示赞赏!
$Servers = import-csv "C:\Scripts\Servers.csv"
while($true) {
ForEach ($Item in $Servers) {
# Unregister-Event $changed.Id -EA 0
$Server = $($Item.Server)
write-host "Checking \\$Server\c$\Scripts now"
#$folder = "c\Scripts"
$filter = "*.html"
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "\\$Server\c$\Scripts\"
$watcher.Filter = "*.html"
$watcher.IncludeSubdirectories = $False
$watcher.EnableRaisingEvents = $true
$created = Register-ObjectEvent $watcher "Created" -Action {
write-host "A new file has been created on $Server $($eventArgs.FullPath) -ForegroundColor Green
}
} #ForEach
write-host "Monitoring for new files. Sleeping for 5 seconds"
Start-Sleep -s 5
} #While
这是我的脚本的单服务器版本,基本上,除了针对一堆服务器运行之外,我想做同样的事情:
$SleepTimer = 15
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "\\FILESERVER\NEWSTUFF\"
$watcher.Filter = "*.html"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
### DEFINE ACTIONS AFTER A EVENT IS DETECTED
$action = {
$path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$changeType, $path"
write-host "$LogLine created"
**RUN EXTERNAL PROGRAM HERE**
add-content -Value $LogLine -path "\\Fileserver\Log.txt"
}
### DECIDE WHICH EVENTS SHOULD BE WATCHED + SET CHECK FREQUENCY
$created = Register-ObjectEvent $watcher "Created" -Action $action
while ($true) {
write-warning "no new files detected. Sleeping for $SleepTimer seconds ..."
start-sleep -s $SleepTimer
}
答案 0 :(得分:1)
我认为每次执行while循环时,都会创建新的文件系统观察程序,它会生成多个警报。这在单个服务器版本的脚本中不会发生
你可以检查一下:{{1}}