PowerShell-在多个未知的自定义值上导出CSV [英] PowerShell - Export-CSV on multiple unknown custom values

查看:81
本文介绍了PowerShell-在多个未知的自定义值上导出CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助开始使用此脚本,并且将尽最大努力解释我要完成的工作.我有一组群集,有些没有自定义配置,有些有一个自定义配置,有些有两个,另一些则有更多.我会将这些自定义配置导出到CSV中,并带有诸如custom1,custom2,custom3等的列标题.

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.

因此,我需要脚本根据群集可能具有的自定义配置创建新的列标题,同时添加NULL或保留没有此类配置的空白群集.这是我脑海中的布局示例.

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.

推荐答案

使用Get-Member获取所有属性名称的列表,并使用Select-Object + Export-CSV使用公共标头导出对象.缺少值的对象会将其设置为null.

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"

这篇关于PowerShell-在多个未知的自定义值上导出CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆