36

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

47

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

3 Comments

Be aware that $PSItem is new to PowerShell v3.
Can't we use Wildcards in the Match cmdlet??
-match search fot the pattern anywhere in the input so you dont have to specify *
33

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 Comment

This should be the accepted answer! Because this will always return an array. In the $f |? {...} case, the return value would be automatically unboxed.
22

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

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.