Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an exit code from a Powershell script only when run non-interactively

Tags:

powershell

I have a lot of scripts that are running as scheduled tasks. So they do a $host.setshouldexit(1) on any failure, which shows up in the task scheduler as the return code.

I also want to be able to run these scripts interactively while debugging and testing. So the $host.setshouldexit() kills my powershell or ISE session.

My question is: how can I detect if a script is running non-interactively? If it is, then I'll use setshouldexit, otherwise it will print the error code or something nondestructive. (Note that I don't want to use [environment]::userinteractive because these scripts are not always running in what the OS thinks is a non-interactive session.)

There is a -noninteractive switch that I'm using for the scheduled tasks. Is there some way I can query that from powershell?

like image 210
scobi Avatar asked Dec 08 '10 19:12

scobi


Video Answer


2 Answers

The $Host.SetShouldExit method should not be necessary, and is actually inconsistent, depending on how you are calling your scripts. Using the keyword exit should get you your exit status.

Using powershell -F script.ps1:

  • exit - works
  • SetShouldExit - ignored

Using powershell -c '.\script.ps1':

  • exit - status reduced to 0 or 1, for success or failure of the script, respectively.
  • SetShouldExit - exits with correct status, but remaining lines in script are still run.

Using powershell -c '.\script.ps1; exit $LASTEXITCODE' [1]:

  • exit - works
  • SetShouldExit - exits with status == 0, and remaining lines in script are still run.

Calling directly from powershell (> .\script.ps1):

  • exit - works
  • SetShouldExit - terminates calling powershell host with given exit status
like image 140
Droj Avatar answered Nov 08 '22 20:11

Droj


Why not just have it take a parameter "testing" which sets the right behavior during your tests? You have a history buffer so it will be hardly any more typing to run.

like image 42
Quaternion Avatar answered Nov 08 '22 19:11

Quaternion