#PSTip Detecting if the console is in Interactive mode

So, in your scripts you want to gather information from the user who runs it and you use the Read-Host cmdlet.

PS> Read-Host Please enter your name

This of course works most of time but there are cases where it won’t work. One case is when the console has been launched using the NonInteractive switch. When that happens you will get this error:

Read-Host : Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available.

How can you tell if the console allows user interaction? One way to avoid that is to detect whether the host that runs the script has been launched in non-interactive mode.  You can find the switches and arguments used to launch your console using the Environment.GetCommandLineArgs method.  With the  GetCommandLineArgs method you can get the array of the command-line arguments for the current process.

C:\> powershell -NoProfile -NoLogo -NonInteractive -Command "[Environment]::GetCommandLineArgs()"

The array includes the executable path along with the command-line arguments used to invoke it (if any). Now we can use that list to check if one of the arguments starts with ‘-noni’ . We check for ‘-noni*’ because there are two ways to specify the the NonInteractive switch, using it’s full name, or using a its short version.  Using a wildcard pattern covers both cases. We then cast the result to a Boolean so we can have a True/False result.

Note that this will work only for console based hosts (powershell.exe), not in the ISE.

[bool]([Environment]::GetCommandLineArgs() -like '-noni*')

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts

%d bloggers like this: