50 lines
2.0 KiB
PowerShell
50 lines
2.0 KiB
PowerShell
function Test-TerminalSupportsANSIEscapes {
|
|
<#
|
|
.SYNOPSIS
|
|
Test if the terminal being used supports ANSI escape sequences
|
|
This matters if we want to avoid spamming characters at the console when they don't benefit us.
|
|
#>
|
|
[CmdletBinding()]
|
|
[OutputType([bool])]
|
|
param (
|
|
)
|
|
|
|
# Implement a runtime caching strategy so we don't keep asking the OS
|
|
if ($script:Test_TerminalSupportsANSIEscapes_set -eq $true) {
|
|
return $script:Test_TerminalSupportsANSIEscapes
|
|
}
|
|
|
|
# Support and honor the request for no-color on output
|
|
# https://no-color.org/
|
|
if ($null -ne (Get-EnvironmentVariable 'NO_COLOR' 6>$null 5>$null 4>$null 3>$null)) {
|
|
$script:Test_TerminalSupportsANSIEscapes_set = $true
|
|
$script:Test_TerminalSupportsANSIEscapes = $false
|
|
return $false
|
|
}
|
|
|
|
# Start with a testable variable, default to int32->0
|
|
$mode = 0
|
|
# Import some headers so we can call the DLLs directly
|
|
$MethodDefinitions = @'
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
public static extern IntPtr GetStdHandle(int nStdHandle);
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
public static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
|
|
'@
|
|
# Get a type library we can play with
|
|
$Kernel32 = Add-Type -MemberDefinition $MethodDefinitions -Name 'Kernel32' -Namespace 'Win32' -PassThru
|
|
# Ask the std_output handle if it knows what mode we are
|
|
$hConsoleHandle = $Kernel32::GetStdHandle(-11) # STD_OUTPUT_HANDLE
|
|
|
|
if ($Kernel32::GetConsoleMode($hConsoleHandle, [ref]$mode)) {
|
|
# We were able to read the value from the std_output handle
|
|
$script:Test_TerminalSupportsANSIEscapes_set = $true
|
|
$script:Test_TerminalSupportsANSIEscapes = ($mode -ne 0)
|
|
return $script:Test_TerminalSupportsANSIEscapes
|
|
} else {
|
|
# We could not read the value, so assume false
|
|
$script:Test_TerminalSupportsANSIEscapes_set = $true
|
|
$script:Test_TerminalSupportsANSIEscapes = $false
|
|
return $false
|
|
}
|
|
} |