powershell - 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"
解决方案
在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
中使用的便利包装函数,请参阅此答案。
推荐阅读
- spring-integration - 使用 MappingJackson2MessageConverter 进行意外的消息转换
- amazon-dynamodb - 按类型从 DynamoDB 中删除项目
- php - 将 cURL 命令行转换为带有 URL 编码的 cURL PHP
- android - (三遍印刷)外部原生构建android studio(Android NDK)
- winapi - 在 32 位进程中使用 GetProcessAffinityMask 寻找 32 cpu 限制的解决方法
- java - 任务运行时显示进度条
- ios - 带有汉堡菜单/左滑动菜单的 UITabBarController
- mysql - 如何计算工作时间以外的时间
- android - onKeyDown 中的键码错误字符
- r - R将地图ShapeFiles合并在一起