1

在 PowerShell V2 中,以下返回当前编辑器的编码

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

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

您可以将编码设置为 ASCII。参看。这个帖子

尝试使用 PowerShell V3 失败。显然 getfield() 不返回任何对象。有什么想法可以解决这个问题吗?

4

2 回答 2

3

任何时候你使用反射来侵入一个类的非公共成员,你都冒着在未来版本中被破坏的风险。这就是这里发生的事情。

也就是说,试试这个:

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

或者,引用整个脚本:

# 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
    }
}
于 2012-01-05T15:03:18.090 回答
1

我以前从未尝试过(在 v2 中),但看起来这在 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
于 2011-12-30T11:29:20.590 回答