如何在创建文件时监视文件夹并触发命令行操作

时间:2017-10-18 11:28:37

标签: powershell

我需要在文件夹中创建文件时触发命令行操作。 在我的情况下,当我创建n - 文件夹中的文件时,脚本开始.cmd n - 次。 如果我有多个创建的文件,如何只启动.cmd脚本?

### SET FOLDER TO WATCH
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "C:\fso"
    $watcher.Filter = "*.xls"
    $watcher.EnableRaisingEvents = $true  

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { Start-Process cmd.exe "/c D:\Users\xfirebg\Desktop\excel\append.cmd"
              }    
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
    Register-ObjectEvent $watcher "Created" -Action $action
    while ($true) {sleep 20}

2 个答案:

答案 0 :(得分:1)

尝试将-Wait选项与Start-Process cmdlet一起使用;这应该强制脚本等待命令执行完毕:

### SET FOLDER TO WATCH
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "C:\fso"
    $watcher.Filter = "*.xls"
    $watcher.EnableRaisingEvents = $true  

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { Start-Process -Wait cmd.exe "/c D:\Users\xfirebg\Desktop\excel\append.cmd"
              }    
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
    Register-ObjectEvent $watcher "Created" -Action $action
    while ($true) {sleep 20}

答案 1 :(得分:0)

这是一种每n个事件而不是每个事件开始您的过程的方法。

我使用一个对象作为参数,我在每次调用中都会收到它。

### SET FOLDER TO WATCH
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "C:\temp"
    $watcher.Filter = "*.tmp"
    $watcher.EnableRaisingEvents = $true  

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { 
      Write-host "coucou $($event.MessageData.counter)";
      $event.MessageData.counter +=1
      if ($event.MessageData.counter % 3 -eq 0){
        Write-host "Bingo !"
      }
    }    
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
    $obj = [PSCustomObject]@{"counter" = 0}
    Register-ObjectEvent $watcher "Created" -Action $action -SourceIdentifier "test" -MessageData $obj
Wait-Event -SourceIdentifier "test"