Reputation: 916
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"}
Upvotes: 36
Views: 104017
Reputation: 339
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
Upvotes: 22
Reputation: 26120
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"}
Upvotes: 46
Reputation: 68243
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.
Upvotes: 33