【发布时间】:2021-03-26 12:35:36
【问题描述】:
您好,我需要在 Powershell 中读取一个 csv 文件并选择某些列并将其保存到新文件中。
这是我的代码
# reading the file
$import = Import-Csv -Path ($file_dir+"Myfile.csv")
# listing out all columns in csv
$import_columnname = $import | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandProperty
'Name'
# grab all columns that I need, using pattern matching
$import_columnneeded = $import_columnname | select-string -Pattern 'stringIdonotNeed|stringIdonotNeed2' -NotMatch
# select the one i need
$import | select -ExpandProperty $import_columnneeded | Export-CSV '.\whereever'
$import_columnneeded 是一个数组,它不适用于 | select -ExpandProperty、select -ExpandProperty 仅适用于字符串。那么我该怎么做才能动态选择我需要的列呢?
【问题讨论】:
-
为什么不使用
Select-Objectcmdlet 的-Property和/或ExcludeProperty参数? -
-ExpandProperty返回扩展属性的值数组。您似乎想输出多列值。您将如何连接/分隔多列值?如果需要所有这些属性扩展,您可以重新考虑原始 CSV 文件的架构。 -
下面提供的答案解决了我的问题,谢谢大家
标签: powershell csv automation