0

I am using Invoke-Expression on each line of a file. If one of the lines causes an error, I would like to stop executing. I have tried using -ErrorAction Stop but it has no effect.

What is supposed to be the effect of the following?

gc -Path "fileWithErrorOnSomeLine.txt" | % {Invoke-Expression "$_" -ErrorAction Stop }

How can one exit the loop immediately if the expression invocation creates an error?

Note: The following change does not stop iterating through the file contents

gc -Path "fileWithErrorOnSomeLine.txt" | % {Invoke-Expression "$_" -ErrorAction Stop } -ErrorAction Stop
Tevya
  • 836
  • 1
  • 10
  • 23

1 Answers1

0

Use try-catch

"tester" > testing.txt
"test2" >> .\testing.txt
"get-childitem" >> .\testing.txt

gc .\testing.txt |  % { 
    try { invoke-expression "$_" -ErrorAction Stop
    }
    catch { 
        write-warning "error : $_ "
        break
    }
}

More info on how to terminate a loop: Terminating a script in PowerShell

Mike L'Angelo
  • 854
  • 6
  • 16