【问题标题】:Change Language in Export-CSV file from SQL Server through PowerShell ISE通过 PowerShell ISE 从 SQL Server 更改 Export-CSV 文件中的语言
【发布时间】: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-Csv cmdlet
  • 崇高!效果很好:) 谢谢!

标签: sql sql-server powershell


【解决方案1】:

Export-CSV 在 PowerShell 5.1 上默认为 ASCII。 -Encoding参数指定目标文件的编码类型,可以选择ASCII, BigEndianUnicode, Default, OEM, Unicode, UTF7, UTF8, UTF32

根据我的评论,UTF8 是一个不错的选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 2023-02-07
    相关资源
    最近更新 更多