3

Outer.ps1:

& "$env:WINDIR\syswow64\WindowsPowerShell\v1.0\powershell.exe" -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command "& '.\Inner.ps1'; Write-Host "BLOCK: $LastExitCode"; exit $LastExitCode"
Write-Host "OUTSIDE: $LastExitCode"

Inner.ps1:

exit 3

Executing Outer.ps1 outputs:

BLOCK: 1
OUTSIDE: 1

What, why? Inner.ps1 clearly exited with exit code 3. What's the problem?

Note: If I change Inner.ps1 to return 0, I receive the following output:

BLOCK: 0
OUTSIDE: 0

Somehow, all other codes than 0 are defaulted to 1, why?

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
D.R.
  • 20,268
  • 21
  • 102
  • 205
  • What happens when you remove the single quotes from `& '.\Inner.ps1'`? I dont think inner is being called. When I remove the single quotes it was working – Matt Feb 25 '15 at 15:06
  • Same result, however, it does not work anymore if Inner.ps1 would have spaces in the name. – D.R. Feb 25 '15 at 15:07
  • Yeah.. was testing in ISE and I only got it to work when I ran Inner manually so I was ruining the test. Back to the drawing board – Matt Feb 25 '15 at 15:11

1 Answers1

4

You have quoting problem:

& "$env:WINDIR\syswow64\WindowsPowerShell\v1.0\powershell.exe" -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command '& ''.\Inner.ps1''; Write-Host "BLOCK: $LastExitCode"; exit $LastExitCode'
Write-Host "OUTSIDE: $LastExitCode"
user4003407
  • 21,204
  • 4
  • 50
  • 60
  • I knew something looked awry but I could get it to work right. Learn something everyday. – Matt Feb 25 '15 at 15:18
  • 1
    To clarify for other readers: $LastExitCode had been replaced before even calling the script! You have to use single quotes here, in order to stop variable replacement! – D.R. Feb 25 '15 at 15:32
  • 1
    More clarification: within single quotes you use single quotes by doubling them (`''.\Inner.ps1''`). Also: the quoting problem with `Write-Host` in the original command has not been a problem because PowerShell automatically concatenated the strings. – D.R. Feb 25 '15 at 15:48