簡體   English   中英

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
}

我認為每次執行 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM