不太了解Powershell“ -Join”和“ ConvertTo-Csv”

时间:2019-12-28 17:49:19

标签: powershell csv join

我有以下代码来创建一个csv并将其显示为表格:

$Keys = ("OrderDate","Region","Rep","Product","Units","Unit Cost","Total")
$Csv = @()    
$Keys | ForEach-Object { 
    $Csv += $_ -Join ","
}
$Csv | ConvertFrom-Csv

我的输出是:

OrderDate
OrderDate,Region
OrderDate,Region,Rep
OrderDate,Region,Rep,Product
OrderDate,Region,Rep,Product,Units
OrderDate,Region,Rep,Product,Units,Unit Cost
OrderDate,Region,Rep,Product,Units,Unit Cost,Total

OrderDate
---------
Region   
Rep      
Product  
Units    
Unit Cost
Total    

我希望这些行被格式化为表格的标题,如下所示:

OrderDate  Region  Rep  ProductUnits  Unit Cost  Total
-----------  --------  ----  ---------------  -----------  ------

1 个答案:

答案 0 :(得分:1)

您要尝试的操作可以这样完成:

$Keys = "OrderDate","Region","Rep","Product","Units","Unit Cost","Total"
$Object = Select-Object -InputObject 0 -Property $Keys

当您在编写脚本时不知道属性是什么时,这通常最有用。输入对象只要是标量值(即不是集合)就没有关系。

要获得您指定的确切输出,您必须做$Object | Format-Table,因为PowerShell默认情况下会列出自定义对象的输出,但是会将对象更改为字符串,以便仅用于显示。

当您知道属性时,一种更通用的创建对象的模式是:

$Object = [PSCustomObject]@{
    "OrderDate" = # Some Value 
    "Region" = # Some Value 
    "Rep" = # Some Value 
    "Product" = # Some Value 
    "Units" = # Some Value 
    "Unit Cost" = # Some Value 
    "Total" = # Some Value 
}

在这里实例化对象并立即分配所需的值。