外部电源外壳脚本仅在调用操作时运行一次



>我正在尝试调用外部 ps 脚本以在每次创建文件时运行。文件的监视和日志记录运行良好,但运行外部脚本的 Invoke-Expression 仅运行一次,即使创建了更多文件也是如此。如何在每次创建新文件时运行外部脚本。

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "c:mypath"
    $watcher.Filter = "*.txt*"
    $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:mypathlog.txt" -value $logline
                Invoke-Expression (start powershell ("C:MyOtherScript.ps1")) ###### This only runs one time even if file is changes and logged
              }
### DECIDE WHICH EVENTS SHOULD BE WATCHED
    Register-ObjectEvent $watcher "Created" -Action $action
    while ($true) {sleep 5}

编辑:这让它工作,以防有人发现自己在这里寻求解决问题

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "c:mypath"
    $watcher.Filter = "*.txt*"
    $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:mypathlog.txt" -value $logline
                Start-Process powershell -argument "C:MyOtherScript.ps1"
              }
### DECIDE WHICH EVENTS SHOULD BE WATCHED
    Register-ObjectEvent $watcher "Created" -Action $action
    #while ($true) {sleep 5}
出于

安全考虑,不建议使用Invoke-Expression而不是使用&。 但是,在您的示例中,我建议Start-Process

Start-Process -FilePath 'powershell' -ArgumentList @('-File','"C:MyOtherScript.ps1"')

最新更新