【问题标题】:Powershell Windows-1251 EncodingPowershell Windows-1251 编码
【发布时间】:2021-12-14 07:55:38
【问题描述】:

当我尝试读取使用俄语编码的文件时 (示例):

$CommentChar = @(";")
$commentRegex = "^\s*([$($CommentChar -join '')].*)$"
switch -regex -file .\myinifile.ini {
$commentRegex {
$value = $matches[1]
Write-host "$value"
}
}

我得到的不是俄语字符,而是: �������� ����, 0 - ��������

如何将编码更改为 Windows 1251?

【问题讨论】:

  • 读取文件的编码,还是写入控制台的编码?
  • 读取文件的编码
  • 您的系统区域设置设置为?
  • 您可能想切换到使用Get-Content单独读取文件,然后您可以使用-Encoding Windows-1251传递编码
  • get-help 获取内容 .... [-Encoding {Unknown |字符串 |统一码 |字节 | BigEndianUnicode | UTF8 | UTF7 | UTF32 | ASCII |默认 |代工 | BigEndianUTF32}] - 没有编码 1251

标签: powershell cyrillic


【解决方案1】:

您可以读取编码代码页为 1251 的文件,如下所示:

# for .Net methods, you need absolute paths
$file = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($pwd, '.\myinifile.ini'))

# get the 1251 encoding object
$cyrillicEnc = [System.Text.Encoding]::GetEncoding("windows-1251")
# read all lines in an array
$contents = [System.IO.File]::ReadAllLines($file, $cyrillicEnc)

# and loop over them using your regex
$CommentChar  = ";"
$commentRegex = "^\s*([$($CommentChar -join '')].*)$"
foreach ($line in $contents) {
    if ($line -match $commentRegex) { Write-Host $matches[1] }
}

假设你的文件看起来像这样:

Доброе утро
  ; Рад познакомиться с тобой
Как дела?

上面代码的结果是

; Рад познакомиться с тобой

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 2013-07-06
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    相关资源
    最近更新 更多