Tim Truty
Tim Truty

Reputation: 145

External powershell scripts only run once when action called

I am trying to call an outside ps script to run every time files are created. The monitoring and logging of files work well, but the Invoke-Expression of running the external script only runs one time even if more files are created. How do I run the external script with every time a new file is created.

### 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:\mypath\log.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}

EDIT: This got it working incase anyone find themselves here looking to solve the porblem

### 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:\mypath\log.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}

Upvotes: 0

Views: 1020

Answers (1)

Maximilian Burszley
Maximilian Burszley

Reputation: 19684

Invoke-Expression is not recommend over using & due to security concerns. In your example, however, I'd suggest Start-Process:

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

Upvotes: 1

Related Questions