【问题标题】:How to filter select certain column from CSV and save to new csv in Powershell?如何过滤从 CSV 中选择特定列并保存到 Powershell 中的新 csv?
【发布时间】: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 -ExpandPropertyselect -ExpandProperty 仅适用于字符串。那么我该怎么做才能动态选择我需要的列呢?

【问题讨论】:

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

标签: powershell csv automation


【解决方案1】:

如果我查看您的代码,您想从原始文件创建一个新的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 2021-12-18
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    相关资源
    最近更新 更多