[英]PowerShell - Want to create fixed width output file for data retrieved from DB using invoke-sqlcmd
$ObjDataSet2 = Invoke-SQLcmd -AbortOnError -Query $Query2 -Server $dbServer -Database $dbName -Username $dbUser -Password $dbPwd
$ObjDataSet2 | ConvertTo-Csv -Delimiter '|' -NoTypeInformation | out-file -Filepath $OutFile -Append
我是 PowerShell 的新手,所以不太了解,這可能是一個簡單直接的解決方案。
我正在使用上述語句從 DB 獲取數據以創建管道分隔文件。 我想生成一個固定寬度的文件而不是管道分隔,我不確定如何以及語法是什么。 以下是上述語句的當前輸出,然后是預期的固定寬度輸出。
電流輸出:
Product_Code|Prodct_ID|Product_Type|Cost
PM1234566|12345|Ellipse|10.13
PM12345672|1234609|Wheel|12.10
PM123456812|123470987|Rod|100.90
PM1234569|12348|Ellipse|14
========
預期輸出:
Product_Code Prodct_ID Product_Type Cost
PM1234566 12345 Ellipse 10.13
PM12345672 1234609 Wheel 12.10
PM123456812 123470987 Rod 100.90
PM1234569 12348 Ellipse 14
==========
所需的列寬:
Product_Code: 1-13
Product_ID: 14-25
Product_Type: 26-41
Cost: 42-50
在此先感謝您的幫助,固定長度的格式在轉換時無法正確顯示,請查看以下詳細信息以了解每個字段的寬度。
這使用-f
字符串格式運算符以及分配列大小和左/右對齊的能力。 負對齊意味着左對齊而不是默認的右對齊。
我手頭沒有你的 SQL 東西,所以我使用你發布的 CSV 作為輸入。 您可以輕松替換它 enuf。 [咧嘴笑]
$Results
集合可以根據需要優雅地輸出到文件中。
# fake reading in a CSV file
# in real life, use Import-CSV
$ProductList = @'
Product_Code|Product_ID|Product_Type|Cost
PM1234566|12345|Ellipse|10.13
PM12345672|1234609|Wheel|12.10
PM123456812|123470987|Rod|100.90
PM1234569|12348|Ellipse|14
'@ | ConvertFrom-Csv -Delimiter '|'
# the "-13" tells the formatter to left-align in a 13 character field
$FormatString = '{0,-13}{1,12}{2,16}{3,9}'
$Results = foreach ($PL_Item in $ProductList)
{
# send the resulting string to the `$Results` collection
$FormatString -f $PL_Item.Product_Code, $PL_Item.Product_ID, $PL_Item.Product_Type, $PL_Item.Cost
}
# send the collection to the screen
$Results
輸出 ...
PM1234566 12345 Ellipse 10.13
PM12345672 1234609 Wheel 12.10
PM123456812 123470987 Rod 100.90
PM1234569 12348 Ellipse 14
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.