【发布时间】:2019-11-15 20:08:04
【问题描述】:
我需要通过 PowerShell ISE 从 SQL Server 导出大量表,其中包含丹麦语条目(意味着我们有 Æ、Ø 和 Å 字母),并且丹麦语字母没有用问号 ??? 代替。
作为一个例子,我有一个名为NavnLeg 的表,其中包含以下数据:
Navn Måned År
--------------------
Jørgen 3 2019
Arne 4 2018
Åse 7 2018
Hans 2 2017
我想通过 Powershell 导出表(因为我有大约 70 个表需要复制到本地驱动器)。
当我在下面运行脚本时,我的 CSV 文件最终如下:
Navn M?ned ?r
--------------------
J?rgen 3 2019
Arne 4 2018
?se 7 2018
Hans 2 2017
这是我当前的脚本,我想在其中声明 CSV 文件应该以某种方式使用丹麦字母。
Get-ChildItem –Path "E:\Backup" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-60))} | Remove-Item
$server = "DEV02"
$database = "Test"
$tablequery = "SELECT name from sys.tables WHERE NAME IN ('NavnLeg')"
$date = (date -f yyyy/MM/dd)
#Declare Connection Variables
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $tablequery
$command.Connection = $connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$connection.Close()
foreach ($Row in $DataSet.Tables[0].Rows)
{
$queryData = "SELECT * FROM [$($Row[0])]"
$extractFile = "E:\Backup\$($date)_$($Row[0]).csv"
$command.CommandText = $queryData
$command.Connection = $connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$connection.Close()
$DataSet.Tables[0] | Export-Csv $extractFile -NoTypeInformation
}
【问题讨论】:
-
尝试将
-Encoding UTF8添加到Export-Csvcmdlet -
崇高!效果很好:) 谢谢!
标签: sql sql-server powershell