源代码中字符串文字的字符编码问题

2024-02-10

$logstring = Invoke-Command -ComputerName $filesServer   -ScriptBlock {
        param(
            $logstring,
            $grp
        )

    $Klassenbuchordner = "KB " + $grp.Gruppe
    $Gruppenordner = $grp.Gruppe
    $share = $grp.Gruppe
    $path = "D:\Gruppen\$Gruppenordner"

    if ((Test-Path D:\Dozenten\01_Klassenbücher\$Klassenbuchordner) -eq $true)
    {$logstring += "Verzeichnis für Klassenbücher existiert bereits"}
    else {
        mkdir D:\Dozenten\01_Klassenbücher\$Klassenbuchordner
        $logstring += "Klassenbuchordner wurde erstellt!"
    }} -ArgumentList $logstring, $grp

我的目标是测试目录是否存在并根据需要创建它。

问题是路径包含德文字母(元音变音),目标服务器无法正确识别这些字母。

例如服务器接收路径"D:\Dozent\01_Klassenbücher"而不是预期的"D:\Dozent\01_Klassenbücher".

如何强制使用正确的 UTF-8 编码?


Note: 远程处理和使用Invoke-Command are 附带的对你的问题.

由于问题发生在字符串字面量在你的源代码 (...\01_Klassenbücher\...),最可能的解释是你的脚本文件被 PowerShell 误解.

In Windows PowerShell, if your script file is de facto UTF-8-encoded but lacks a BOM, the PowerShell engine will misinterpret any non-ASCII-range characters (such as ü) in the script.[1]

所以:将脚本重新保存为 UTF-8with BOM.

Note:

  • 在按需安装、跨平台中不再严格需要 UTF-8 BOMPowerShell(核心)7+ https://github.com/PowerShell/PowerShell/blob/master/README.md版本(始终如一defaults到(BOM-less)UTF-8),但如果您希望脚本在以下环境中运行,则仍然需要bothPowerShell 版本。

为什么应该将脚本保存为带有 BOM 的 UTF-8:

视觉工作室代码和其他现代编辑器创建 UTF-8 文件无物料清单默认情况下,这就是导致 Windows PowerShell 中出现问题的原因。

By contrast, the PowerShell ISE creates "ANSI"-encoded[1] files, which Windows PowerShell - but not PowerShell Core - reads correctly.

您只能使用“ANSI”编码的文件:

  • 如果您的脚本永远不会在 PowerShell 中运行Core- 未来所有的开发工作都将去往何处。

  • 如果你的脚本永远不会在一台机器上运行不同的“ANSI”代码页有效。

  • 如果您的脚本不包含无法用“ANSI”代码页表示的字符(例如表情符号)。

鉴于这些限制,始终创建 PowerShell 脚本是最安全且面向未来的带 BOM 的 UTF-8.
(或者,您可以使用 UTF-16(始终保存withBOM),但如果您主要使用 ASCII/“ANSI”范围字符(这可能在 PS 脚本中),则会导致文件大小膨胀)。


如何让 Visual Studio Code 创建 UTF-8 文件with-BOM对于 PowerShell 脚本默认情况下:

注意:自 v1.11.0 起仍需要以下内容VSCode 的 PowerShell 扩展 https://marketplace.visualstudio.com/items?itemName=ms-vscode.PowerShell,但并不是说有一个建议延期defaultPowerShell 文件转换为 UTF-8with BOM 在 GitHub 上 https://github.com/PowerShell/vscode-powershell/issues/1771.

Add the following to your settings.json file (from the command palette (Ctrl+Shift+P, type settings and select Preferences: Open Settings (JSON)):

"[powershell]": {
  "files.encoding": "utf8bom"
}

请注意,设置的范围有意为电源外壳仅文件,因为你不会想要all文件默认为 UTF-8with BOM,考虑到 Unix 平台上的许多实用程序既不期望也不知道如何处理这样的 BOM。


[1] In the absence of a BOM, Windows PowerShell defaults to the encoding of the system's current "ANSI" code page, as determined by the legacy system locale; e.g., in Western European cultures, Windows-1252.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

源代码中字符串文字的字符编码问题 的相关文章

随机推荐