Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter a string array (or list) in PowerShell using the 'Match' cmdlet?

Tags:

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"} 
like image 836
Abhijeet Nagre Avatar asked Jan 05 '13 14:01

Abhijeet Nagre


People also ask

How do you filter an array of objects in PowerShell?

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.

Which cmdlet is used to filter another cmdlets output?

The Where-Object cmdlet allows you to filter the result based on any property value, including nested properties.

How do you filter an item from an array?

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.


2 Answers

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"} 
like image 127
Loïc MICHEL Avatar answered Sep 30 '22 19:09

Loïc MICHEL


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.

like image 24
mjolinor Avatar answered Sep 30 '22 18:09

mjolinor