1

Since, i am a beginner, i 've no much hands-on to the powershell programming.Although i had a script developed to insert data from an array to the csv file as follows:

#Following is the array
$InventoryReport = New-Object -TypeName PSobject -Property @{
                        ComputerName = "1myComputerName"
                        DomainName = "2myComputerDomain"
                        Manufacturer = "3myComputerManufacturer"
}

#Now to export the data to csv, i am using following:
$InventoryReport |Select-Object -Property ComputerName, DomainName, Manufacturer | Export-Csv -Path "c:\abc.csv" -NoTypeInformation -ErrorAction Stop

#This works fine

and the output of above is :

"ComputerName","DomainName","Manufacturer" "1myComputerName","2myComputerDomain","3myComputerManufacturer"

.... Now, i don't want this , i want the ouput to appear in columnar fashion i.e.

"ComputerName","1myComputerName"
"DomainName","2myComputerDomain"
"Manufacturer","3myComputerManufacturer"

What code changes should be done to achieve this. ?

4

2 回答 2

1

要么你想要 CSV,你已经有了,或者你想要一个自定义的 txt 文件。如果你想要后者,试试这个:

$comp = gwmi win32_computersystem

@"
"ComputerName","$($comp.Name)"
"DomainName","$($comp.Domain)"
"Manufacturer","$($comp.Manufacturer)"
"@ | Out-File test.txt

下面的 test.txt 输出示例。我有一台非域的定制电脑,所以不用担心这些值。

"ComputerName","GRAIMER-PC"
"DomainName","WORKGROUP"
"Manufacturer","System manufacturer"

编辑我建议你了解 CSV 是什么。请记住,CSV 不是文件格式,它是普通文本文件中使用的格式样式。.csv扩展名只是为了让人们知道文本文件使用 csv 样式。查看维基百科Technet

在 CSV 文件中,每个对象由对象的属性值的逗号分隔列表表示。属性值被转换为字符串(通过使用对象的 ToString() 方法),因此它们通常由属性值的名称表示。Export-CSV 不导出对象的方法。

导出文件的格式如下:

-- CSV 文件的第一行包含字符串“#TYPE”,后跟对象的完全限定名称,例如#TYPE System.Diagnostics.Process。要禁止显示此行,请使用 NoTypeInformation 参数。

- CSV 文件的下一行代表列标题。它包含第一个对象的所有属性名称的逗号分隔列表。

--文件的附加行由逗号分隔的每个对象的属性值列表组成。

于 2013-05-21T09:43:29.717 回答
1

你可以尝试这样的事情:

$InventoryReport | Format-List ComputerName, DomainName, Manufacturer `
  | Out-String -Stream `
  | ? { $_ -ne '' } `
  | % { $_ -replace '\s+:\s+', '","' -replace '(^|$)', '"' }
于 2013-05-21T17:17:08.293 回答