2

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.

What I have now is:

    $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

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.

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.