#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()" C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -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*')Share on: