|
1 | 1 | # Hack! https://gist.github.com/lzybkr/f2059cb2ee8d0c13c65ab933b75e998c |
2 | 2 |
|
3 | | -if ($IsWindows -eq $false) { |
| 3 | +# We do not need to set the console mode in PowerShell Core on any platform. |
| 4 | +# On Windows, PowerShell Core added this support in this PR: |
| 5 | +# https://github.com/PowerShell/PowerShell/pull/2991 |
| 6 | +if ($PSVersionTable.PSVersion.Major -ge 6) { |
4 | 7 | function Set-ConsoleMode { |
5 | 8 | [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] |
6 | 9 | param() |
7 | 10 | } |
| 11 | + |
8 | 12 | return |
9 | 13 | } |
10 | 14 |
|
11 | | -Add-Type @" |
| 15 | +$consoleModeSource = @" |
12 | 16 | using System; |
13 | 17 | using System.Runtime.InteropServices; |
14 | 18 |
|
@@ -85,19 +89,29 @@ function Set-ConsoleMode |
85 | 89 | $StandardInput |
86 | 90 | ) |
87 | 91 |
|
88 | | - if ($ANSI) |
89 | | - { |
90 | | - $outputMode = [NativeConsoleMethods]::GetConsoleMode($false) |
91 | | - $null = [NativeConsoleMethods]::SetConsoleMode($false, $outputMode -bor [ConsoleModeOutputFlags]::ENABLE_VIRTUAL_TERMINAL_PROCESSING) |
| 92 | + begin { |
| 93 | + # Add the NativeConsoleMethods type but only if it hasn't already been added to this session. |
| 94 | + # Deferring the Add-Type to the first time this function is called, speeds up module import. |
| 95 | + if (!('NativeConsoleMethods' -as [System.Type])) { |
| 96 | + Add-Type $consoleModeSource |
| 97 | + } |
| 98 | + } |
92 | 99 |
|
93 | | - if ($StandardInput) |
| 100 | + end { |
| 101 | + if ($ANSI) |
94 | 102 | { |
95 | | - $inputMode = [NativeConsoleMethods]::GetConsoleMode($true) |
96 | | - $null = [NativeConsoleMethods]::SetConsoleMode($true, $inputMode -bor [ConsoleModeInputFlags]::ENABLE_VIRTUAL_TERMINAL_PROCESSING) |
| 103 | + $outputMode = [NativeConsoleMethods]::GetConsoleMode($false) |
| 104 | + $null = [NativeConsoleMethods]::SetConsoleMode($false, $outputMode -bor [ConsoleModeOutputFlags]::ENABLE_VIRTUAL_TERMINAL_PROCESSING) |
| 105 | + |
| 106 | + if ($StandardInput) |
| 107 | + { |
| 108 | + $inputMode = [NativeConsoleMethods]::GetConsoleMode($true) |
| 109 | + $null = [NativeConsoleMethods]::SetConsoleMode($true, $inputMode -bor [ConsoleModeInputFlags]::ENABLE_VIRTUAL_TERMINAL_PROCESSING) |
| 110 | + } |
| 111 | + } |
| 112 | + else |
| 113 | + { |
| 114 | + [NativeConsoleMethods]::SetConsoleMode($StandardInput, $Mode) |
97 | 115 | } |
98 | | - } |
99 | | - else |
100 | | - { |
101 | | - [NativeConsoleMethods]::SetConsoleMode($StandardInput, $Mode) |
102 | 116 | } |
103 | 117 | } |
0 commit comments