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"}
You can build a filter for Where-Object via a scriptblock. To use a scriptblock as a filter, you'd use the FilterScript parameter. This parameter allows you to create and pass a scriptblock to the FilterScript parameter which is then executed.
The Where-Object cmdlet allows you to filter the result based on any property value, including nested properties.
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
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"}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With