Pergunta

In PowerShell V2 the following returns the Encoding of the current editor

$a=$psise.CurrentPowerShellTab.Files[0]
$a.gettype().getfield("encoding","nonpublic,instance").getvalue($a) 

and with

$a=$psise.CurrentPowerShellTab.Files[0]
$a.gettype().getfield("encoding","nonpublic,instance").setvalue($a,[text.encoding]::ascii) 

you can set the encoding to ASCII. cf. this post

Trying the same with PowerShell V3 fails. Obviously getfield() returns no object. Any ideas to fix this ?

Foi útil?

Solução

Any time you use reflection to hack into non-public members of a class, you're running the risk it would break in a future release. That's what's happened here.

That said, try this:

$psise.CurrentPowerShellTab.Files | % {
    $_.gettype().getfield("doc","nonpublic,instance").getvalue($_).Encoding = [text.encoding]::ascii
}

Or, to quote the whole script:

# watch for changes to the Files collection of the current Tab
register-objectevent $psise.CurrentPowerShellTab.Files collectionchanged -action {
    # iterate ISEFile objects
    $event.sender | % {
         # set encoding on private ITextDocument field to ASCII
         $_.gettype().getfield("doc","nonpublic,instance").getvalue($_).Encoding = [text.encoding]::ascii
    }
}

Outras dicas

I never tried it before (in v2) but looks like this is working in CTP2:

PS> $a = $psise.CurrentPowerShellTab.Files[0]
PS> $a.Encoding

BodyName          : utf-8
EncodingName      : Unicode (UTF-8)
HeaderName        : utf-8
WebName           : utf-8
WindowsCodePage   : 1200
IsBrowserDisplay  : True
IsBrowserSave     : True
IsMailNewsDisplay : True
IsMailNewsSave    : True
IsSingleByte      : False
EncoderFallback   : System.Text.EncoderReplacementFallback
DecoderFallback   : System.Text.DecoderReplacementFallback
IsReadOnly        : True
CodePage          : 65001


PS> $a.Save([text.encoding]::ascii)
PS> $a.Encoding

IsSingleByte      : True
BodyName          : us-ascii
EncodingName      : US-ASCII
HeaderName        : us-ascii
WebName           : us-ascii
WindowsCodePage   : 1252
IsBrowserDisplay  : False
IsBrowserSave     : False
IsMailNewsDisplay : True
IsMailNewsSave    : True
EncoderFallback   : System.Text.EncoderReplacementFallback
DecoderFallback   : System.Text.DecoderReplacementFallback
IsReadOnly        : True
CodePage          : 20127
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top