如何在Powershell中筛选CSV中的特定列并保存为新CSV?

如何在Powershell中筛选CSV中的特定列并保存为新CSV?,powershell,csv,automation,Powershell,Csv,Automation,您好,我需要在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

您好,我需要在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_columnRequired
是一个数组,它不与|
选择-ExpandProperty
一起工作,
选择-ExpandProperty
仅对字符串起作用。那么,如何才能动态选择所需的列呢?

如果我查看您的代码,您希望在跳过某些列的同时从原始列创建一个新的csv文件

例如,如果这是CSV中的数据

Username  Identifier Password Firstname Lastname Department  Location  
--------  ---------- -------- --------- -------- ----------  --------  
booker12  9012       12se74   Rachel    Booker   Sales       Manchester
grey07    2070       04ap67   Laura     Grey     Depot       London    
johnson81 4081       30no86   Craig     Johnson  Depot       London    
jenkins46 9346       14ju73   Mary      Jenkins  Engineering Manchester
smith79   5079       09ja61   Jamie     Smith    Engineering Manchester
你可以用这个

# a regex string that contains all headers you don't want combined with regex OR '|'
$notNeeded = 'Password|Location|Identifier'

$file_dir = 'D:\Test'
$fileIn   = Join-Path -Path $file_dir -ChildPath "MyFile.csv"
$fileOut  = Join-Path -Path $file_dir -ChildPath "MyNewFile.csv"

# import the original file
$import = Import-Csv -Path $fileIn

# get an array of column headers excluding the ones you don't want
$columns = $import[0].PSObject.Properties.Name | Where-Object { $_ -notmatch $notNeeded }

# output a new csv file with all remaining headers
$import | Select-Object $columns | Export-Csv -Path $fileOut -NoTypeInformation
制作:

Username  Firstname Lastname Department 
--------  --------- -------- ---------- 
booker12  Rachel    Booker   Sales      
grey07    Laura     Grey     Depot      
johnson81 Craig     Johnson  Depot      
jenkins46 Mary      Jenkins  Engineering
smith79   Jamie     Smith    Engineering

为什么不使用cmdlet的
-Property
和/或
ExcludeProperty
参数?
-ExpandProperty
返回扩展属性的值数组。您似乎想要输出多列值。您将如何连接/分隔多个值列?如果需要所有这些属性扩展,您可以重新考虑原始CSV文件的架构。下面提供的答案解决了我的问题,谢谢大家