You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell创建无BOM的UTF8文件?解决SQL Agent脚本报错

解决PowerShell导出CSV含UTF-8 BOM的问题

错误原因

你使用UTF8NoBOM参数报错,是因为该参数仅在PowerShell Core(6.0及以上)中支持,而SQL Server Agent默认搭载的是Windows PowerShell(5.1及以下版本),此版本的Export-Csv cmdlet的Encoding参数可选集合里没有UTF8NoBOM选项,因此触发验证错误。

解决方案

方法一:使用.NET类直接写入无BOM的UTF-8文件

绕过Export-Csv的编码限制,先将查询结果转为CSV格式字符串,再用无BOM的UTF-8编码写入文件:

$query = "select * from [server].[database].[view]"
# 将查询结果转换为CSV格式字符串
$csvContent = Invoke-Sqlcmd -QueryTimeout 0 -Query $query | ConvertTo-Csv -NoTypeInformation
# 创建无BOM的UTF-8编码对象
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
# 写入文件
[System.IO.File]::WriteAllLines("[FilePath]\[FileName].csv", $csvContent, $utf8NoBom)

方法二:先导出带BOM文件,再移除BOM

如果依赖Export-Csv的原生功能,可先导出带BOM的文件,再读取内容并以无BOM编码重新写入:

$query = "select * from [server].[database].[view]"
$tempFilePath = "[FilePath]\temp.csv"
# 导出带BOM的临时CSV文件
Invoke-Sqlcmd -QueryTimeout 0 -Query $query | Export-Csv -NoTypeInformation -Encoding UTF8 -Path $tempFilePath
# 读取临时文件内容
$csvContent = Get-Content -Path $tempFilePath -Raw
# 创建无BOM的UTF-8编码对象
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
# 写入最终无BOM的CSV文件
[System.IO.File]::WriteAllText("[FilePath]\[FileName].csv", $csvContent, $utf8NoBom)
# 删除临时文件
Remove-Item -Path $tempFilePath -Force

内容的提问来源于stack exchange,提问作者Deb Richardson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:05:09