Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prompt error in remote PSSession #708

Closed
fullenw1 opened this issue Oct 20, 2019 · 15 comments · Fixed by #727
Closed

Prompt error in remote PSSession #708

fullenw1 opened this issue Oct 20, 2019 · 15 comments · Fixed by #727

Comments

@fullenw1
Copy link

fullenw1 commented Oct 20, 2019

System Details

  • posh-git version/path: 0.7.3 C:\Program Files\WindowsPowerShell\Modules\posh-git\0.7.3
  • PowerShell version: 5 1 14409 1018
  • Git version: 1.9.5.msysgit.0
  • Operating system name and version: Win32NT 6.3.9600.0 Microsoft Windows NT 6.3.9600.0

Issue Description

When I am in a remote PSSession, the prompt displays an error message:

C:\Repo [Error: Exception setting "OutputEncoding": "The handle is invalid.
"][ComputerName]: >

When I am in a local PowerShell session on the same computer, the prompt works fine.

C:\Repo [master ≡]>

@rkeithhill
Copy link
Collaborator

Can you repro that and then execute $error[0] | Format-List * -Force and paste the output here.

@fullenw1
Copy link
Author

PSMessageDetails :
Exception : System.Management.Automation.SetValueInvocationException: Exception setting "OutputEncoding": "The handle is invalid.
" ---> System.IO.IOException: The handle is invalid.

                       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
                       at System.Console.set_OutputEncoding(Encoding value)
                       at CallSite.Target(Closure , CallSite , Type , Object )
                       --- End of inner exception stack trace ---
                       at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
                       at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
                       at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
                       at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)

TargetObject :
CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
FullyQualifiedErrorId : ExceptionWhenSetting
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at Invoke-Utf8ConsoleCommand, C:\Program Files\WindowsPowerShell\Modules\posh-git\0.7.3\Utils.ps1: line 42
at Get-GitStatus, C:\Program Files\WindowsPowerShell\Modules\posh-git\0.7.3\GitUtils.ps1: line 236
at , C:\Program Files\WindowsPowerShell\Modules\posh-git\0.7.3\GitPrompt.ps1: line 330
at , C:\Program Files\WindowsPowerShell\Modules\posh-git\0.7.3\GitPrompt.ps1: line 324
at Global:Write-VcsStatus, C:\Program Files\WindowsPowerShell\Modules\posh-git\0.7.3\GitPrompt.ps1: line 324
at , C:\Program Files\WindowsPowerShell\Modules\posh-git\0.7.3\posh-git.psm1: line 56
at , : line 1
PipelineIterationInfo : {}

@labrunning
Copy link

I'm getting the same on the following;

  • git version 2.24.0.windows.2
  • Windows Server 2012 RC2
  • PowerShell Version 5.1.14409.1005
  • post-git 0.7.3

@rkeithhill
Copy link
Collaborator

This is the offending code:

    $currentEncoding = [Console]::OutputEncoding
    $errorCount = $global:Error.Count
    try {
        # A native executable that writes to stderr AND has its stderr redirected will generate non-terminating
        # error records if the user has set $ErrorActionPreference to Stop. Override that value in this scope.
        $ErrorActionPreference = 'Continue'
        if ($currentEncoding.IsSingleByte) {
            [Console]::OutputEncoding = [Text.Encoding]::UTF8
        }
        & $cmd
    }
    finally {
        if ($currentEncoding.IsSingleByte) {
            [Console]::OutputEncoding = $currentEncoding # <<< errors here
        }

We are trying to revert the OutputEncoding to its original value. I wonder if we need to be checking the value of $currentEncoding before trying to set it back. Will need to look into this some more. It would be nice to know what the value of $currentEncoding is in this case.

@labrunning
Copy link

Here's what my [Console]::OutputEncoding is;

IsSingleByte      : True  
BodyName          : iso-8859-1  
EncodingName      : Western European (Windows)  
HeaderName        : Windows-1252  
WebName           : Windows-1252  
WindowsCodePage   : 1252  
IsBrowserDisplay  : True  
IsBrowserSave     : True  
IsMailNewsDisplay : True  
IsMailNewsSave    : True  
EncoderFallback   : System.Text.InternalEncoderBestFitFallback  
DecoderFallback   : System.Text.InternalDecoderBestFitFallback  
IsReadOnly        : True  
CodePage          : 1252  

I am remoting onto the server via Enter-PSSession if that's of any relevance.

@fullenw1
Copy link
Author

I have exactly the same OutputEncoding as labrunning.

And indeed you've found the piece of code generating the error :)

[Console]::OutputEncoding = [Text.Encoding]::UTF8
Exception setting "OutputEncoding": "The handle is invalid.
"
At line:1 char:1
+ [Console]::OutputEncoding = [Text.Encoding]::UTF8
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], SetValueInvocationException
    + FullyQualifiedErrorId : ExceptionWhenSetting

@rkeithhill
Copy link
Collaborator

Can one of you try changing Utils.ps1 line 42 from this:

            [Console]::OutputEncoding = $currentEncoding

to

            try { [Console]::OutputEncoding = $currentEncoding } catch {}

I'm not crazy about just swallowing the exception but if it can get past this and still work correctly ...

@fullenw1
Copy link
Author

fullenw1 commented Dec 2, 2019

Unfortunately, I get the same error.

@rkeithhill
Copy link
Collaborator

How about this:

try { $ErrorActionPreference = 'Stop'; [Console]::OutputEncoding = $currentEncoding } catch {}

@fullenw1
Copy link
Author

fullenw1 commented Dec 3, 2019

Still the same error :(

@rkeithhill
Copy link
Collaborator

Huh. And the error you get indicates it is coming from the line (42) that you modified in Utils.ps1? Is it possible the error is originating from 36? Maybe comment out line 36 and see if it still fails.

@labrunning
Copy link

Commenting out line 36 with the last suggested change to line 42 now works for me.

@fullenw1
Copy link
Author

fullenw1 commented Dec 4, 2019

Yep! works for me too :)

rkeithhill added a commit that referenced this issue Dec 8, 2019
Would be better to detect when we would get the IOException but not
sure how to do that.

Fix #708
@rkeithhill
Copy link
Collaborator

Since I'm not able to repro this, can one of you see if my PR branch above fixes the issue for you? I'd like to verify that before merging it.

@o-l-a-v
Copy link

o-l-a-v commented Dec 23, 2021

I had this problem in PowerShell ISE too.

$Global:OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()

Worked fine from a Windows PowerShell terminal, also PowerShell 7.2.1 from Microsoft Store. But in PowerShell ISE it gave:

Exception setting "OutputEncoding": "The handle is invalid.
Some more error details
# Exception:
## Exception\ErrorRecord:
Exception setting "OutputEncoding": "The handle is invalid.
"
## Exception\WasThrownFromThrowStatement:
False
## Exception\Message:
Exception setting "OutputEncoding": "The handle is invalid.
"
## Exception\InnerException:
System.IO.IOException: The handle is invalid.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.Console.set_OutputEncoding(Encoding value)
   at CallSite.Target(Closure , CallSite , Type , Object )
## Exception\TargetSite:
Void CheckActionPreference(System.Management.Automation.Language.FunctionContext, System.Exception)
## Exception\StackTrace:
at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
## Exception\Source:
System.Management.Automation
## Exception\HResult:
-2146233087
# CategoryInfo:
## CategoryInfo\Category:
NotSpecified
## CategoryInfo\Reason:
SetValueInvocationException
# FullyQualifiedErrorId:
## FullyQualifiedErrorId\Length:
20
## FullyQualifiedErrorId\Chars:
char Chars(int index) {get;}
# InvocationInfo:
## InvocationInfo\ScriptLineNumber:
2
## InvocationInfo\OffsetInLine:
5
## InvocationInfo\HistoryId:
-1
## InvocationInfo\Line:
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
## InvocationInfo\PositionMessage:
At line:2 char:5
+     [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
## InvocationInfo\PipelineLength:
0
## InvocationInfo\PipelinePosition:
0
## InvocationInfo\ExpectingInput:
False
## InvocationInfo\CommandOrigin:
Internal
# ScriptStackTrace:
## ScriptStackTrace\Length:
35
## ScriptStackTrace\Chars:
char Chars(int index) {get;}
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

Then I figured out by goofing around that, if you've had any output from CMD first, like so for instance (see under), then it worked.

$null = cmd /c ''

So in my jank script for using winget-cli to update certain apps if an update is available, due to the output of winget-cli being utf8, I now use following before using winget-cli:

$null = cmd /c ''
$Global:OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()

I thought this find might help others, so figured I should write this somewhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants