检查文件夹是否也被复制

时间:2017-02-22 04:43:06

标签: powershell scheduled-tasks shared-directory

我想运行一个脚本,在Windows上使用一堆文件(例如一堆.pdf' s)执行特定程序。问题是我从其他位置接收这些文件到共享文件夹。因此,我需要检查此共享文件夹并仅在所有文件从我无法控制的另一个驱动器完成复制时执行该程序。

无论如何要这样做?我所有的搜索都让我使用了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}

1 个答案:

答案 0 :(得分:3)

根据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和闭包进行一些额外的研究。

希望有所帮助。