我需要在文件夹中创建文件时触发命令行操作。在我的情况下,当我创建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}
尝试将-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}
这是一种每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"