PowerShell-要为使用invoke sqlcmd从DB检索的数据创建固定宽度的输出文件吗
我是全新的PowerShell,所以不知道太多,这可能是一个简单的直截了当的解决方案 我使用上述语句从DB获取数据,以创建管道分隔文件。我想生成一个固定宽度的文件,而不是以管道分隔的文件,我不知道如何生成,语法是什么。下面是上述语句的当前输出,后面是预期的固定宽度输出 电流输出: ======== 预期产出: ========== 所需的列宽:PowerShell-要为使用invoke sqlcmd从DB检索的数据创建固定宽度的输出文件吗,powershell,Powershell,我是全新的PowerShell,所以不知道太多,这可能是一个简单的直截了当的解决方案 我使用上述语句从DB获取数据,以创建管道分隔文件。我想生成一个固定宽度的文件,而不是以管道分隔的文件,我不知道如何生成,语法是什么。下面是上述语句的当前输出,后面是预期的固定宽度输出 电流输出: ======== 预期产出: ========== 所需的列宽: 提前感谢您的帮助,固定长度的格式在转换时不会正确显示,请查看下面每个字段宽度的详细信息。这使用了-f字符串格式运算符以及分配列大小和左/右对齐的能力。负
提前感谢您的帮助,固定长度的格式在转换时不会正确显示,请查看下面每个字段宽度的详细信息。这使用了
-f
字符串格式运算符以及分配列大小和左/右对齐的能力。负对齐意味着左对齐,而不是默认的右对齐
我手头没有你的SQL资料,所以我使用了你发布的CSV作为输入。你可以很容易地更换它。[咧嘴笑]
$Results
集合可以根据需要优雅地输出到文件中
Product_Code: 1-13
Product_ID: 14-25
Product_Type: 26-41
Cost: 42-50
输出
# 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
你好,李,谢谢你的解决方案,我能够在我的代码中插入建议的格式语句,它工作起来很有魅力,现在唯一的问题是格式语句正在删除列标题,是否有办法在文件中保留列标题。@user12547230-您需要读取文件的第一行以获取标题,然后将其添加为输出的第一行。您可以对标题使用相同的格式字符串。//<带有制表符分隔符的代码>导出CSV对于固定宽度不起作用,因为它不知道除制表符以外的任何内容。
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
# 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