【问题标题】:PowerShell : Set-Content Replace word and Encoding UTF8 without BOMPowerShell : Set-Content Replace word and Encoding UTF8 without BOM
【发布时间】:2021-03-09 19:15:01
【问题描述】:

我想在 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"

【问题讨论】:

  • 如果没有特殊字符,set-content 的默认编码是一样的。

标签: powershell utf-8


【解决方案1】:
  • PowerShell (Core) 7+ 中,您将获得 BOM-less UTF-8 文件默认情况下-Encoding utf8-Encoding utf8NoBom 明确表示默认值;要使用 BOM,需要-Encoding utf8BOM

  • 不幸的是,在 Windows PowerShell 中,您必须直接调用 .NET API 才能获得无 BOM 的 UTF-8,因为 -Encoding utf8 仅生成带有 BOM 的 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-less UTF-8 文件的 Windows PowerShell 中使用的围绕 Out-File 的便捷包装函数,请参阅 this answer

【讨论】:

    猜你喜欢
    • 2022-12-01
    • 2013-07-15
    • 2014-08-23
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 2012-08-24
    • 2018-11-17
    • 1970-01-01
    相关资源
    最近更新 更多