首页 > 解决方案 > PowerShell : Set-Content Replace word 和 Encoding UTF8 without BOM

问题描述

我想在 csv 文件中将 \ 转义为 \\ 以上传到 Redshift。按照预期,遵循简单的 PowerShell 脚本可以将 $TargetWord \ 替换为 $ReplaceWord \\ ,但使用 bom 导出 utf-8 有时会导致 Redshift 复制错误。

任何建议将不胜感激以改进它。先感谢您。

Exp_Escape.ps1

Param(
    [string]$StrExpFile,
    [string]$TargetWord,
    [string]$ReplaceWord
)

# $(Get-Content "$StrExpFile").replace($TargetWord,$ReplaceWord) | Set-Content -Encoding UTF8 "$StrExpFile"

标签: powershellutf-8

解决方案


  • PowerShell (Core) 7+中,默认情况下您将获得无 BOM 的UTF-8 文件;并明确表达该默认值;要使用 BOM,是必需的。-Encoding utf8-Encoding utf8NoBom-Encoding utf8BOM

  • 不幸的是,在Windows PowerShell中,您必须直接调用 .NET API 才能获得无 BOM 的 UTF-8,因为只生成带有 BOM-Encoding utf8的 UTF-8 文件(不支持其他相关值)。utf8

# In order for .NET API calls to work as expected,
# file paths must be expressed as *full, native* paths.
$OutDir = Split-Path -Parent $StrExpFile
if ($OutDir -eq '') { $OutDir = '.' }
$strExpFileFullPath = Join-Path (Convert-Path $OutDir) (Split-Path -Leaf $StrExpFile)

# Note: .NET APIs create BOM-less UTF-8 files *by default*
[IO.File]::WriteAllLines(
  $strExpFileFullPath,
  (Get-Content $StrExpFile).Replace($TargetWord, $ReplaceWord)
)

以上使用System.IO.File.WriteAllLines方法。

有关在创建无 BOM 的UTF-8 文件的Windows PowerShellOut-File中使用的便利包装函数,请参阅此答案


推荐阅读