我有一个基于新对象System.IO.FileSystemWatcher的脚本,它在我的家庭文件服务器上监视文件夹中的新文件,并运行外部应用程序,但现在我将扩展新对象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
}发布于 2017-02-09 13:12:27
我认为每次执行while循环时,都会创建新的文件系统监视器,该监视器会生成多个警报,而在您的单服务器版本的脚本中不会发生.which
你能检查一下这个吗:
$Servers = import-csv "C:\Scripts\Servers.csv"
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
}
}
while ($true) {
write-host "Monitoring for new files. Sleeping for 5 seconds"
Start-Sleep -s 5
} #Whilehttps://stackoverflow.com/questions/42127022
复制相似问题