2015-04-07 41 views
0

如何在PowerShell中將Unicode-y字符導出爲CSV?看起來像-Encoding UTF8應該做的伎倆。我有以下對象在PowerShell中:通過PowerShell將Unicode中的字符從SQL導出爲CSV

$data = @{"column" = "1/13/14->1/26/14"} 

什麼我實際上得到的是一個單字符的Unicode向右箭頭從一個SQL查詢來,而不是短跑,大於號我在上面已經輸入,但我似乎無法將右箭頭複製粘貼到Stack Overflow編輯器。我相信箭頭人物被成功地從SQL獲取到PowerShell的,因爲我可以登錄到PowerShell控制檯:

enter image description here

不管怎樣,我想這個對象導出爲CSV:

$table = $data.getEnumerator() | foreach{ 
    New-Object PSObject -Property ([ordered]@{column = $_.Value}) 
} 
$table | export-csv export.csv -NoTypeInformation -Encoding UTF8 

問題是,右箭頭無法正確編碼。在Notepad ++中查看CSV,我看到箭頭應該是太熟悉的黑色SUB框。

enter image description here

我已經嘗試了所有微軟的Export-CSV page列出的出口爲CSV編碼,但無濟於事。我在這裏錯過了關於CSV和編碼的內容?這種低級別的數據處理應該在PowerShell的控制之下。是否有可能需要在SQL - > PowerShell步驟中進行一些額外的編碼管理?在那裏我使用非常直接的ADO.Net:

function Invoke-Sql { 
param(
    [string] $dataSource = ".\SQLEXPRESS", 
    [string] $database = "MasterData", 
    [string] $sqlCommand = $(throw "Please specify a query.") 
) 

    $connectionString = "Data Source=$dataSource; " + 
     "Integrated Security=true; " + 
     "Initial Catalog=$database" 

    $connection = New-Object System.Data.SqlClient.SQLConnection($connectionString) 
    $command = New-Object System.Data.SqlClient.SQLCommand($sqlCommand,$connection) 
    $connection.Open() 

    $adapter = New-Object System.Data.SqlClient.SqlDataAdapter $command 
    $dataset = New-Object System.Data.DataSet 
    $adapter.Fill($dataSet) | Out-Null 

    $connection.Close() 
    return $dataSet 
} 
+0

你可以將文件壓縮並上傳到某個地方以便我們查看它嗎? –

回答

0

不是一個真正的答案,但我不能發表評論中的圖片。我無法用Win8.1/PowerShell 4.0複製該問題。我用一個屬性創建了一個對象,該對象包含一個字符串,它的值是右側的箭頭字符。代碼示例:

PS C:\Windows\System32\WindowsPowerShell\v1.0> [pscustomobject]@{name="hello$([char]8594)there"} 

name                                                             
----                                                             
hello→there                                                           


PS C:\Windows\System32\WindowsPowerShell\v1.0> [pscustomobject]@{name="hello$([char]8594)there"}|Export-Csv -NoTypeInformation c:\temp\test.csv -Encoding UTF8 

當我看到在記事本文件++是輸出完全一樣預期:

Notepad++ Screenshot
所以我想知道什麼字符SQL的輸出,因爲它不會出現是Unicode向右箭頭,字符8594.

我現在唯一真正的建議是關閉並重新打開PowerShell,以確保一切都是新鮮的,然後輸出到您以前沒有使用過的新文件以確保現有規範沒有編碼問題ic文件。

+0

原來,SQL給了我'nchar(26)'(「substitute」),而不是字符8594(「右箭頭」)。嘗試在SQL中重現以下內容:select nchar(26)as unicodeForSubstitute,nchar(8594)as unicodeForRightArrow – user941238