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

问题描述 投票:2回答:2

我需要在文件夹中创建文件时触发命令行操作。在我的情况下,当我创建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}
powershell
2个回答
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}

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"
© www.soinside.com 2019 - 2024. All rights reserved.