使用 Powershell 为包含特殊字符的 outlook 签名创建 txt 文件时出现编码问题

Encoding problem when creating a txt-file for outlook signatures that contains special characters, using Powershell

我在使用为 Microsoft Outlook 创建签名的 powershell 脚本时遇到了一些问题。我对 powershell 不是很熟悉,正在尝试修改现有脚本。我遇到的问题是未格式化邮件的 txt 文件中的编码。我在瑞典,所以它需要能够使用瑞典字符 (åäö)。脚本输出的 txt 文件确实包含正确的 åäö,但是当在 Outlook 中打开签名时,这些字符会出现问题,ä 显示为 ä,ö 显示为 ö 等等。 经过一些谷歌搜索后,似乎 Outlook 使用 Windows-1252,但我无法让 powershell 输出到该编码。

这是现在的脚本;

$stream = [System.IO.StreamWriter] "$FolderLocation\test.txt"
$stream.WriteLine("--- OBS TEST ---")
$stream.WriteLine("Med vänlig hälsning")

$stream.WriteLine(""+$strName+"")

$stream.WriteLine(""+$strTitle+"")
$stream.WriteLine("")

$stream.WriteLine(""+$strCompany+"")

$stream.WriteLine(""+$strStreet+"")

$stream.WriteLine(""+$strPostCode+" "+$strCity+"")

$stream.WriteLine("")

if($strPhone){$stream.WriteLine("Telefon:    " + $strPhone+"")}
if($strMobile){$stream.WriteLine("Mobil:      " + $strMobile+"")}
$stream.WriteLine("")

$stream.WriteLine("E-post:     "+ $strEmail+"")

$stream.WriteLine("Hemsida:    "+ $strWebsite+"")

$stream.close()

这个输出的文件在记事本中打开时看起来完全没问题。

我试过将输出文件重新编码成各种编码,但没有成功;

get-content -path $FolderLocation\test.txt | out-file -filePath $FolderLocation$strName.txt -encoding UTF8

关于如何解决这个问题的任何提示?

Add-content 而不是 writeline 应该可以。 Add-Content 默认使用 Windows-1252 编码。瑞典字符将被正确存储。

add-content test.txt "--- OBS TEST ---"
add-content test.txt "Med vänlig hälsning"

add-content test.txt ""+$strName+""

add-content test.txt ""+$strTitle+""
add-content test.txt ""

add-content test.txt ""+$strCompany+""

add-content test.txt ""+$strStreet+""

add-content test.txt ""+$strPostCode+" "+$strCity+""

add-content test.txt ""

if($strPhone){add-content test.txt "Telefon:    " + $strPhone+""}
if($strMobile){add-content test.txt "Mobil:      " + $strMobile+""}
add-content test.txt ""

add-content test.txt "E-post:     "+ $strEmail+""

add-content test.txt "Hemsida:    "+ $strWebsite+""

如果您想坚持使用您的 StreamWriter 方法,请注意 Theo's 建议并 在流创建期间明确指定所需的 Windows-1252 编码:

$stream = [IO.StreamWriter]::new(
     "$FolderLocation\test.txt",          # file path
     $false,                              # do not append, create a new file
     [Text.Encoding]::GetEncoding(1252)   # character encoding
)

但是,考虑到逐行写行是多么麻烦,我建议切换到 单个可扩展 here-string,你可以将它作为一个整体输送到 Set-Content:

@"
--- OBS TEST ---
Med vänlig hälsning
$strName
$strTitle

$strCompany
$strStreet
$strPostCode $strCity

$(
  $lines = $(if ($strPhone)  { "Telefon:    " + $strPhone  }),
           $(if ($strMobile) { "Mobil:      " + $strMobile }),
           ''
  $lines -ne $null -join [Environment]::NewLine
)
E-post:     $strEmail

Hemsida:    $strWebsite
"@ | Set-Content $FolderLocation$strName.txt  # See note re PowerShell *Core*

WindowsPowerShell中,Set-Content默认为系统的活动ANSI代码页,假定为Windows-1252。

但是,在 PowerShell Core 中,始终默认为(无 BOM)UTF-8,您必须明确指定编码:

Set-Content -Encoding ([Text.Encoding]::GetEncoding(1252)) $FolderLocation$strName.txt