Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell test for noninteractive mode

Tags:

I have a script that may be run manually or may be run by a scheduled task. I need to programmatically determine if I'm running in -noninteractive mode (which is set when run via scheduled task) or normal mode. I've googled around and the best I can find is to add a command line parameter, but I don't have any feasible way of doing that with the scheduled tasks nor can I reasonably expect the users to add the parameter when they run it manually. Does noninteractive mode set some kind of variable or something I could check for in my script?

Edit: I actually inadvertently answered my own question but I'm leaving it here for posterity.

I stuck a read-host in the script to ask the user for something and when it ran in noninteractive mode, boom, terminating error. Stuck it in a try/catch block and do stuff based on what mode I'm in.

Not the prettiest code structure, but it works. If anyone else has a better way please add it!

like image 902
matthew Avatar asked Mar 16 '12 13:03

matthew


1 Answers

I didn't like any of the other answers as a complete solution. [Environment]::UserInteractive reports whether the user is interactive, not specifically if the process is interactive. The api is useful for detecting if you are running inside a service. Here's my solution to handle both cases:

function Assert-IsNonInteractiveShell {     # Test each Arg for match of abbreviated '-NonInteractive' command.     $NonInteractive = [Environment]::GetCommandLineArgs() | Where-Object{ $_ -like '-NonI*' }      if ([Environment]::UserInteractive -and -not $NonInteractive) {         # We are in an interactive shell.         return $false     }      return $true } 
like image 102
VertigoRay Avatar answered Dec 19 '22 01:12

VertigoRay