Skip to content

Instantly share code, notes, and snippets.

@SamErde
Last active January 12, 2026 21:31
Show Gist options
  • Select an option

  • Save SamErde/4ae30a56f8a805507b017212b811f64f to your computer and use it in GitHub Desktop.

Select an option

Save SamErde/4ae30a56f8a805507b017212b811f64f to your computer and use it in GitHub Desktop.
function Test-UserInteractive {
<#
.SYNOPSIS
Determines whether the current PowerShell session is interactive.
.DESCRIPTION
Evaluates the current PowerShell session to determine if it is running in an interactive mode.
This function checks for:
- Non-interactive command-line switches
- CI/CD environment variables (GitHub Actions, GitLab CI, Azure DevOps, etc.)
- Container environments (Docker, Kubernetes, Windows containers)
Returns $true if the session is interactive, $false otherwise.
.EXAMPLE
Test-UserInteractive
Returns $true if running in an interactive PowerShell session.
.EXAMPLE
if (Test-MtUserInteractive) {
Write-Host "Running interactively"
}
Conditionally executes code based on whether the session is interactive.
.OUTPUTS
System.Boolean
Returns $true if the session is interactive, $false if non-interactive.
#>
[CmdletBinding()]
[OutputType([bool])]
param ()
# Check if environment variables indicate running in a CI/CD environment.
$CiCdEnvironment = @(
# GitHub Actions
$env:GITHUB_ACTIONS -eq 'true',
# GitLab CI
$env:GITLAB_CI -eq 'true',
# Azure DevOps
$env:TF_BUILD -eq 'true',
# Bitbucket Pipelines
$null -ne $env:BITBUCKET_BUILD_NUMBER,
# Jenkins
$null -ne $env:JENKINS_URL,
# CircleCI
$env:CIRCLECI -eq 'true',
# Travis CI
$env:TRAVIS -eq 'true',
# TeamCity
$null -ne $env:TEAMCITY_VERSION
)
# Check if environment variables indicate running within a container environment.
$ContainerEnvironment = @(
# Check for Docker
(Test-Path -Path '/.dockerenv'),
# Check for common container environment variables
$env:KUBERNETES_SERVICE_HOST -ne $null,
# Check for Windows container
$env:CONTAINER -eq 'true'
)
# Analyze command-line arguments for non-interactive indicators.
$CommandLineArguments = [System.Environment]::GetCommandLineArgs()
$HasNonInteractive = $false
$HasCommand = $false
$HasNoExit = $false
foreach ($Argument in $CommandLineArguments) {
switch -Regex ($Argument) {
'(?i)^-NonInteractive$' { $HasNonInteractive = $true; break }
'(?i)^-Command$' { $HasCommand = $true }
'(?i)^-NoExit$' { $HasNoExit = $true }
}
}
# Return true if the session is interactive (does not match non-interactive criteria).
$IsInteractive = -not (
$HasNonInteractive -or # Explicitly non-interactive mode.
($HasCommand -and -not $HasNoExit) -or # If -Command is specified without -NoExit, it's non-interactive.
($CiCdEnvironment -contains $true) -or # Running in a CI/CD environment.
($ContainerEnvironment -contains $true) # Running in a container environment.
)
$IsInteractive
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment