How to filter an array of strings (or a list) in PowerShell using the Match cmdlet?

I am trying to filter CSV files. But the following script throws an error. How to indicate that I want to perform a mapping for each String object?

I tried different combinations, but to no avail.

$FileNames = [System.IO.Directory]::GetFiles("C:\Users\anagre\Desktop") $FileNames = $FileNames | Where { -match "*.csv"} 
+10
source share
3 answers

The -match operator is both a comparison operator and an array operator, depending on its input object.

If it is a scalar, it returns a boolean value. If it is an array, it returns all elements of the array that match the pattern.

 @($Filenames) -match '*.csv' 

Use array syntax to ensure that you still get the array if Get-ChildItem returns only one file name. Otherwise, you will get $True back instead of the file name if it matches.

+7
source

Try it:

 $FileNames = Get-ChildItem -Path "C:\Users\anagre\Desktop" -Filter *.csv 

In the above code, you did not use $ PSItem ($ _) in the where clause, and if you want to use a wildcard, you must use the -like operator:

 $FileNames|where{$_ -like "*.csv"} 

or

 $FileNames|where{$_ -match ".csv"} 
+19
source

The simplest (and most accurate) way that I found this was as follows:

 $filename.where{$_ -match '.csv'} 

or search only the specified hash table column

 $filename.where{$_.location -match '.csv'} 

Then get only the pieces you need

 $filename.where{$_.location -match '.csv'} | select User,Filename,Filetype 

etc.

0
source

All Articles