Powershell test for noninteractive mode

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
}

You can check how powershell was called using Get-WmiObject for WMI objects:

(gwmi win32_process | ? { $_.processname -eq "powershell.exe" }) | select commandline

#commandline
#-----------
#"C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe" -noprofile -NonInteractive

UPDATE: 2020-10-08

Starting in PowerShell 3.0, this cmdlet has been superseded by Get-CimInstance

(Get-CimInstance win32_process -Filter "ProcessID=$PID" | ? { $_.processname -eq "pwsh.exe" }) | select commandline

#commandline
#-----------
#"C:\Program Files\PowerShell\6\pwsh.exe"

Tags:

Powershell