Reputation: 153
Random letters showing in ppowershell script error making it so hard to find where the error stems from
Upvotes: 2
Views: 181
Reputation: 439787
Note: The following applies to PowerShell (Core) v7.2+:
What you're seeing are ANSI / VT (Virtual Terminal) escape sequences that are typically used to make terminals render text with formatting, notably colored.
If you render strings containing such escape sequences verbatim, such as via a message box, you'll get garbled text as in your screenshot, so you'll need to instruct PowerShell not to use these escape sequences.
Since it looks like you're calling your PowerShell script from the outside, via the pwsh.exe
, the Windows PowerShell CLI, a simple way to instruct PowerShell not to use these escape sequences it to define the NO_COLOR
environment variable (with any value, but 1
makes conceptual sense) before calling pwsh.exe
.[1]
An alternative is to execute $PSStyle.OutputRendering='PlainText'
:
Either: as part of a -Command
(-c
) argument passed to pwsh.exe
Or: By placing this call at the top of your script.
For more information, see the conceptual about_ANSI_Terminals help topic.
Demonstration of the problem:
# Call the PowerShell (Core) 7.2+ CLI and provoke an error,
# then render the output via a message box:
(New-Object -ComObject WScript.Shell).Popup(
(pwsh -c '1 / 0')
)
Result - note the garbled text:
The problem goes away if you define NO_COLOR
first:
$env:NO_COLOR=1
(New-Object -ComObject WScript.Shell).Popup(
(pwsh -c '1 / 0')
)
Result - no more garbled text:
[1] If you define it for the calling process, the pwsh
child process will inherit it. Unlike the $PSStyle.OutputRendering
setting, NO_COLOR
must already exist when the pwsh
process is created in order to be effective. In cases where you're calling from a Unix shell, you can define the environmant variable in a command-scoped way, e.g. NO_COLOR=1 pwsh -c '1 / 0'
Upvotes: 4