PowerShell - Export-CSV on multiple unknown custom values

岁酱吖の 提交于 2020-01-05 10:07:43

问题


I need help getting started on this script and will do the best to explain what I am trying to accomplish. I have a set of clusters, some have no custom config, some have one custom config, some have two, and other have more. I would to export these custom configs into a CSV, with column headers like custom1, custom2, custom3, etc.

So I need the script to create new column headers based on how many custom config a cluster might have, while either adding NULL or leaving blank cluster that don't have such config. Here is an example of a layout in my head.

ClusterName Custom1 Custom2 Custom3 Custom4
ABC         123     456     NULL    NULL
DEF         NULL    NULL    NULL    NULL
GHI         123     456     789     abc

I don't want to statically create the column before hand, because the custom config could really vary and I need to programmatically allow the script to create the columns based on the data retrieved. I hope all this makes sense and thanks for any help.


回答1:


Get a list of all propertynames using Get-Member and use Select-Object + Export-CSV to export the objects using a common header. Objects missing a value will set it to null.

$a = @()
$a += [pscustomobject]@{ClusterName="ABC";Custom1=123;Custom2=456}
$a += [pscustomobject]@{ClusterName="DEF"}
$a += [pscustomobject]@{ClusterName="GHI";Custom1=123;Custom2=456; Custom3=789;Custom4="abc"}    

$properties = $a | ForEach-Object { 
    $_ | Get-Member -MemberType Property, NoteProperty
} | Select-Object -ExpandProperty Name -Unique

$a | Select-Object $properties | Export-Csv test.csv -NoTypeInformation

test.csv

"ClusterName","Custom1","Custom2","Custom3","Custom4"
"ABC","123","456",,
"DEF",,,,
"GHI","123","456","789","abc"



回答2:


Your can dynamically create any object within your script. That object can then be piped out to export-csv, whatever columns have been created will get exported.




回答3:


I had to do something similar - where I was reporting on hard disks for VMs. Some VMs had up to 15 HDDs, while others only had a couple. The CSV was only creating 5 columns.

I added an extra field in the script to count the number of disks for each VM, then at the end, sorted the data by number of disks (descending). Then I could send the output to Out-Gridview or ConvertTo-CSV.

Example count column:

$disks = $vm.guest.disk
$disks = $disks.count
$Details | Add-Member -Name NumberOfDisks -Value $disks -Membertype NoteProperty

Example data sort before piping elsewhere:

$MyCollection = $MyCollection | Sort-Object NumberOfDisks -Descending

$MyCollection piped to Out-Gridview - note the NULL/empty columns:



来源:https://stackoverflow.com/questions/22120265/powershell-export-csv-on-multiple-unknown-custom-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!