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?
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
- worksSetShouldExit
- ignoredUsing 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
- worksSetShouldExit
- exits with status == 0, and remaining lines in script are still run.Calling directly from powershell (> .\script.ps1
):
exit
- worksSetShouldExit
- terminates calling powershell host with given exit statusWhy 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With