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



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

这是现在看起来的脚本;

$stream = [System.IO.StreamWriter] "$FolderLocationtest.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 $FolderLocationtest.txt | out-file -filePath $FolderLocation$strName.txt -encoding UTF8

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

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

$stream = [IO.StreamWriter]::new(
"$FolderLocationtest.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。

但是,在始终默认为(无BOM(UTF-8的PowerShellCore中,您必须显式指定编码:

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

添加内容而不是写行应该有效。 默认情况下,添加内容使用 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+""

最新更新