2012-Oct-15, Monday

mellowtigger: (penguin coder)
Can a powershell script determine if it's running in an interactive environment or not? I have a few methods that get close to the answer, but nothing offers satisfying certainty yet.

CodeExplanation
$host.namepowershell.exe yields 'ConsoleHost'
powershell_gui.exe yields 'Windows PowerShell ISE Host'
Each program, however, can operate in either batch or interactive conditions.

$process = gwmi win32_process -filter "ProcessID=$pid"
$batch = $process.commandline -match "-NonInteractive"

If someone programs the scheduled task with the "-NonInteractive" parameter, then the script can successfully read that parameter.  It's not the default, though.
$host.runspace.runspacestateinfo
$host.runspace.runspaceavailability
I always find the state info as 'Opened'. In gui conditions, availability has always been 'Busy'. In batch conditions, though, it is 'Available'.  Can I rely on this indicator?

I need to know, because I want to separate hardcoded userid/password combinations from my scripts.  I want to put them into the parameter of the scheduled task instead.  When testing those same scripts interactively, though, I want the script to prompt me for the data that it didn't receive through parameters.

Any script stuck at a user prompt is a Bad Thing [tm] when running in batch mode, since no one will ever answer it.  Using the '-NonInteractive' parameter is a good idea for all batch PowerShell scripts for this reason.  It seems to just suppress any command (or the partial execution of it) that would require user input.  I didn't even know this parameter existed until today.  It would have prevented an error in a production script that got stuck prompting for permission to delete a subfolder that I never expected to be there.  My script would have skipped that subfolder and gone on its merry way doing other things.

It still doesn't answer my question, though.  Is there a reliable way to tell if my script is running interactively or not?  Yes, it's a bit like asking which kind of virtual reality I live in, but sometimes it is important to know the distinction.  :)  Does anyone have the answer?

edit 2012.10.19: I forgot to mention previously, but someone on g+ pointed me to a webpage where contributors mentioned a few ways of dealing with this problem.  Among the solutions was one that works:  [environment]::userinteractive.

Profile

mellowtigger: (Default)
mellowtigger

About

September 2025

S M T W T F S
 1234 56
78910 111213
14 15 16 17181920
21222324252627
282930    

Most Popular Tags

Powered by Dreamwidth Studios
Page generated 2025-Sep-18, Thursday 01:42 pm