說我運行這個:
$HOME_DATABASE = 'mydb'
$params = @{
'Database' = $HOME_DATABASE
'ServerInstance' = 'mydb'
'Username' = 'myuser'
'Password' = 'mypass'
'Query' = 'select * from sometable'
}
$queryresults = Invoke-Sqlcmd @params
我希望輸出看起來像:
Name Date Number of Records 95th Percentile 99.5th Percentile 100th Percentile
---- ---- ----------------- --------------- ----------------- ----------------
asdf 2022-10-02 00:00:00.000 1234 5678 9012 12345
分隔欄位的是選項卡。
我試過這個,但它不包括連字符/虛線。
$queryresults |ConvertTo-Csv -NoTypeInformation -delimiter "$query_result_separator" | `
ForEach-Object {$_ -Replace('"','')} | `
Out-file c:\temp\$($query_attachment_filename) -fo -en ascii
其他人說匯出-csv,然后回傳并替換檔案中的引號。有沒有更好的辦法?
uj5u.com熱心網友回復:
Export-Csv和(前者ConvertTo-Csv在記憶體中的對應物)在設計上不會在它們的標題行和資料行之間創建分隔線,因為這樣一行的唯一目的是使資料對人類友好,而 CSV / TSV 資料用于程式化處理。
- 要獲得這樣的行,您必須手動插入它。
此外,兩個 cmdlet "..."- 包含所有欄位值 -總是在Windows PowerShell中,默認情況下在PowerShell (Core) 7 中。
在PowerShell (Core) 7 中,您可以
-UseQuotes Never選擇退出此行為。在Windows PowerShell中,您需要洗掉
"字符。事后,就像您在自己的解決方案嘗試中所做的那樣。
適用于兩個PowerShell 版本的解決方案:
$i = 0
$queryresults |
ConvertTo-Csv -NoTypeInformation -Delimiter "`t" |
ForEach-Object {
$_ -replace '"' # output with " chars. removed
# If it was the first, i.e. the *header* row that was just output,
# construct and output the desired separator row.
if ($i -eq 0) {
($_ -replace '"' -split "`t").ForEach({ '-' * $_.Length }) -join "`t"
}
}
根據需要通過管道傳輸Set-Content(這比 更可取Out-File,因為它是要保存的字串- 請參閱此答案)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/518216.html
