2017-02-22 128 views
1

我想運行一個腳本,該腳本在使用一堆文件(例如一堆.pdf)的窗口上執行特定程序。問題是我正在將這些文件從另一個位置接收到共享文件夾。所以我需要檢查這個共享文件夾,並且只有當所有文件都完成了我不能控制的另一個驅動器的拷貝時才執行該程序。檢查一個文件夾是否被拷貝過

無論如何要做到這一點?我所有的搜索都讓我使用PowerShell和這樣的腳本,除了我的操作記錄文件外,我需要執行程序,但我不知道如何做到這一點,最後複製的文件/文件夾已經完成。

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO 
    $watcher = New-Object System.IO.FileSystemWatcher 
    $watcher.Path = "C:\Users\User\Desktop\monitor_this" 
    $watcher.Filter = "*.*" 
    $watcher.IncludeSubdirectories = $true 
    $watcher.EnableRaisingEvents = $true 

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED 
    $action = { $path = $Event.SourceEventArgs.FullPath 
       $changeType = $Event.SourceEventArgs.ChangeType 
       $logline = "$(Get-Date), $changeType, $path" 
       Add-content "C:\Users\User\Desktop\log.txt" -value $logline 
       }  
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
    Register-ObjectEvent $watcher "Created" -Action $action 
    Register-ObjectEvent $watcher "Changed" -Action $action 
    Register-ObjectEvent $watcher "Deleted" -Action $action 
    Register-ObjectEvent $watcher "Renamed" -Action $action 
    while ($true) {sleep 5} 
+0

使用滑動計時器技術:將$ action代碼內部的計時器重置爲新的時間(例如5秒),以便在5秒內沒有任何內容被修改時實際執行。 – wOxxOm

+0

所以我在添加內容之前添加了$ timer.Interval = 20000。但是,一旦定時器用完,我怎麼才能得到添加內容或其他任何部分? – Soorman

+0

添加內容應該在計時器的「動作」內 – wOxxOm

回答

2

基於wOxxOm的意見,我想上面的例子擴展:

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO 
 
    $watcher = New-Object System.IO.FileSystemWatcher 
 
    $watcher.Path = "C:\Users\User\Desktop\monitor_this" 
 
    $watcher.Filter = "*.*" 
 
    $watcher.IncludeSubdirectories = $true 
 
    $watcher.EnableRaisingEvents = $true 
 

 
### Create timer 
 
    $timer = new-object timers.timer 
 
    $timer.Interval = 5000 #5 seconds 
 
    $timer.Enabled = $true 
 

 
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED 
 
    $fileWatcherAction = { 
 
     # Reset the timer every time the file watcher reports a change 
 
     write-host "Timer Elapse Event: $(get-date -Format ‘HH:mm:ss’)" 
 
     $timer.Stop() 
 
     $timer.Start() 
 
    } 
 

 
    $timerAction = { $path = $Event.SourceEventArgs.FullPath 
 
       $changeType = $Event.SourceEventArgs.ChangeType 
 
       $logline = "$(Get-Date), $changeType, $path" 
 
       Add-content "C:\Users\User\Desktop\log.txt" -value $logline 
 
       }  
 

 
### When timer fires timerAction is called 
 
    Register-ObjectEvent $timer "Elapsed" -Action $timerAction 
 

 
### DECIDE WHICH EVENTS SHOULD BE WATCHED, every call of below events resets the timer 
 
    Register-ObjectEvent $watcher "Created" -Action $fileWatcherAction 
 
    Register-ObjectEvent $watcher "Changed" -Action $fileWatcherAction 
 
    Register-ObjectEvent $watcher "Deleted" -Action $fileWatcherAction 
 
    Register-ObjectEvent $watcher "Renamed" -Action $fileWatcherAction 
 
    while ($true) {Start-Sleep 5}

什麼實際上,我不知道是$timer封閉處理,也許你還有一些關於Powershell和關閉的研究。

希望有所幫助。