PowerShell:设置内容替换单词和编码 UTF8 没有 BOM [英] PowerShell : Set-Content Replace word and Encoding UTF8 without BOM

查看:97
本文介绍了PowerShell:设置内容替换单词和编码 UTF8 没有 BOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to escape \ to \\ in csv file to upload to Redshift. Following simple PowerShell script can replace $TargetWord \ to $ReplaceWord \\ , as expected, but export utf-8 with bom and sometimes causes the Redshift copy error.

如有任何建议以改进它,我们将不胜感激.提前致谢.

Any advice would be appreciated to improve it. Thank you in advance.

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

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

推荐答案

  • PowerShell (Core) 7+中,您将获得BOM-less UTF-8 文件默认-Encoding utf8-Encoding utf8NoBom 明确表示该默认值;要使用 BOM,需要 -Encoding utf8BOM.

    • In PowerShell (Core) 7+, you would get BOM-less UTF-8 files by default; -Encoding utf8 and -Encoding utf8NoBom express that default explicitly; to use a BOM, -Encoding utf8BOM is needed.

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

      In Windows PowerShell, unfortunately, you must directly call .NET APIs to get BOM-less UTF-8, because -Encoding utf8 only produces UTF-8 files with BOM (and no other utf8-related values are supported).

      # 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)
      )
      

      以上使用系统.IO.File.WriteAllLines 方法.

      The above uses the System.IO.File.WriteAllLines method.

      有关 Out-File 的便利包装函数,用于在 Windows PowerShell 中创建BOM-less UTF-8 文件,请参阅这个答案.

      For a convenience wrapper function around Out-File for use in Windows PowerShell that creates BOM-less UTF-8 files, see this answer.

      这篇关于PowerShell:设置内容替换单词和编码 UTF8 没有 BOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆