35

I am trying to filter CSV files. But the following script is giving an error. How do I specify that I want to run match on each String object?

I tried various combinations, but without result.

$FileNames = [System.IO.Directory]::GetFiles("C:\Users\anagre\Desktop")

$FileNames = $FileNames | Where { -match "*.csv"}

3 Answers 3

43

Try this:

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

In your above code you didn't use the $PSItem ($_) in your where clause, and if you want to use a wildchar you have got to use the -like operator:

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

or

$FileNames|where{$_ -match ".csv"}
3
  • Be aware that $PSItem is new to PowerShell v3.
    – Keith Hill
    Commented Jan 5, 2013 at 17:59
  • Can't we use Wildcards in the Match cmdlet?? Commented Jan 5, 2013 at 20:03
  • 3
    -match search fot the pattern anywhere in the input so you dont have to specify * Commented Jan 11, 2013 at 14:58
32

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

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

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

Use the array syntax to ensure that you still get an array if there's only one filename returned by Get-ChildItem. Otherwise, you'll get back $True instead of the filename if it matches.

1
  • 3
    This should be the accepted answer! Because this will always return an array. In the $f |? {...} case, the return value would be automatically unboxed.
    – plaes
    Commented Dec 19, 2017 at 8:37
19

The simplest (and tidiest) way I found to do this was as follows:

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

or to only search within a given column of a hashtable

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

Then get just the bits you need

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

etc

Not the answer you're looking for? Browse other questions tagged or ask your own question.