提问人:Kenny 提问时间:2/9/2017 最后编辑:Kenny 更新时间:9/3/2018 访问量:1055
New-Object System.IO.FileSystemWatcher 多个服务器
New-Object System.IO.FileSystemWatcher multiple servers
问:
我有一个基于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
}
答:
1赞
ClumsyPuffin
2/9/2017
#1
我认为每次执行 while 循环时,都会创建新的文件系统观察程序,该观察程序会生成多个警报,这在您的单服务器版本的脚本中不会发生
你能检查一下吗?
$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
} #While
评论
0赞
Kenny
2/9/2017
就是这样!超级简单的修复!非常感谢:-)
评论