我有一个 SQL Server SQL 代理作业,它使用 PowerShell 和以下脚本来创建 csv 文件,但是该脚本在我的输出中放置了隐藏的字节顺序标记 (BOM)。如何删除 BOM?
$query = "select * from [server].[database].[view]"
Invoke-Sqlcmd -QueryTimeout 0 -Query $query | Export-Csv -NoTypeInformation -Encoding UTF8 -Path "[FilePath\[FileName].csv"
我尝试将代码更改为:
Invoke-Sqlcmd -QueryTimeout 0 -Query $query | Export-Csv -NoTypeInformation -Encoding UTF8NoBom -Path "[FilePath\[FileName].csv"
但收到以下错误:
...PowerShell 返回的错误信息是:“无法验证参数‘Encoding’上的参数。”参数“UTF8NoBOM”不属于 ValidateSet 属性指定的集合“Unicode.UTF7.UTF8.ASCII.UTF32.BigEndianUnicode.DefaultOEM”...
Xedni指出的Stack Overflow问题有足够的信息来解决问题,但在CSV的上下文中,如果你想使用Lucero的答案,它会变得有点复杂。
不要使用Export-Csv -NoTypeInformation
,而是使用
ConvertTo-Csv -NoTypeInformation
首先将文件的文本保存到变量中,然后使用 Lucero 的答案写入文件。
$FileText = Invoke-Sqlcmd -QueryTimeout 0 -Query $query | ConvertTo-Csv -NoTypeInformation
Set-Content ([Text.UTF8Encoding]::new().GetBytes($FileText)) -Encoding Byte -PSPath "[FilePath\[FileName].csv"