可能结合.csv where - 对象过滤器? [英] Possible to combine .csv where-object filters?

查看:165
本文介绍了可能结合.csv where - 对象过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据位置栏筛选.csv档案。该列具有各种位置条目,我只需要来自包含某些位置的行的信息,然后将该信息导出到单独的.csv文件。我可以得到它的工作通过搜索.CSV文件多次与每个位置过滤器,但我没有运气时,试图将它结合到1搜索。

I'm trying to filter a .csv file based on a location column. The column has various location entries and I only need information from the rows that contain certain locations, that information then gets exported out to a separate .csv file. I can get it to work by searching the .csv file multiple times with each location filter, but I haven't had any luck when trying to combine it into 1 search.

我现在是:

    $csv = Import-Csv "${filepath}\temp1.csv"
    $csv | Where-Object location -like "co*" | select EmployeeNumber | Export-Csv "${filepath}\disablelist.csv" -NoTypeInformation
    $csv | Where-Object location -like "cc*" | select EmployeeNumber | Export-Csv "${filepath}\disablelist.csv" -Append -NoTypeInformation
    $csv | Where-Object location -like "dc*" | select EmployeeNumber | Export-Csv "${filepath}\disablelist.csv" -Append -NoTypeInformation
    $csv | Where-Object location -like "mf*" | select EmployeeNumber | Export-Csv "${filepath}\disablelist.csv" -Append -NoTypeInformation



< d喜欢有类似下面的东西。我没有得到任何错误,但我得到的是一个空白的.csv文件:

What I'd like to have is something like below. I don't get any errors with it, but all I get is a blank .csv file:

    $locations = "co*","cc*","dc*","mf*"
    $csv = Import-Csv "${filepath}\temp1.csv"
    $csv | Where-Object location -like $locations | select EmployeeNumber | Export-Csv "${filepath}\disablelist.csv" -NoTypeInformation

这里有一段时间,我通常能够从我发现的一个脚本,弗兰肯斯坦一起,但我似乎找不到任何东西。感谢您的帮助。

I've been lurking here for a while and I'm usually able to frankenstein a script together from what I find, but I can't seem to find anything on this. Thanks for your help.

推荐答案

您可以替换多个 -like 使用交替的正则表达式进行单个 -match 测试:

You can replace multiple -like tests with a single -match test using an alternating regex:

$csv = Import-Csv "${filepath}\temp1.csv"
$csv | Where-Object {$_.location -match  '^(co|cc|dc|mf)'} |
   select EmployeeNumber | 
   Export-Csv "${filepath}\disablelist.csv" -NoTypeInformation

可以从字符串数组构建正则表达式:

You can build that regex from a string array:

$locations = 'co','cc','dc','mf'
$LocationMatch = '^({0})' -f ($locations -join '|')

$csv = Import-Csv "${filepath}\temp1.csv"
$csv | Where-Object { $_.location -match  $LocationMatch } |
   select EmployeeNumber | 
   Export-Csv "${filepath}\disablelist.csv" -NoTypeInformation

这篇关于可能结合.csv where - 对象过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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