2017-02-09 52 views
1

我有一個基於New-Object System.IO.FileSystemWatcher的腳本,用於監視我的主文件服務器上的文件夾以查找新文件,並運行外部應用程序,但現在我正在擴展New-Object System.IO.FileSystemWatcher的用法,以監視一組多個服務器(來自.csv的輸入)。New-Object System.IO.FileSystemWatcher多個服務器

只要檢測到事件,我就得到了下面的代碼,但是當檢測到新文件時,它會多次爲新文件生成警報。任何想法我怎麼能得到它只是產生一個警報?我在想這就是我的循環結構?

任何幫助表示讚賞!

$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

對不起,我應該更清楚。我正在爲同一臺服務器和文件創建多個警報。當我運行單一版本的腳本時,我只是得到每個服務器的一個警報,直到創建一個新文件。 – Kenny

+0

好的。我將如何重新排序/重新寫入,所以我只能獲得服務器上創建的每個新文件的一個警報,但能夠保持其無限期運行? – Kenny

+0

我已將我的單一服務器版本添加到原始文章中: – Kenny

回答

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