PowerShell: Use Where-Object to Filter for Strings that End With


Often you may want to use the Where-Object cmdlet in PowerShell to filter for files that end with a specific string.

You can use the following basic syntax to do so:

Get-ChildItem 'c:/my/folder' | Where-Object { $_.Basename -match 'text$'}

Here is what this particular example does:

  • First, use Get-ChildItem to get all files from the path specified.
  • Then, use Where-Object to filter for files where the file name (without the extension) ends with the string text.

Note that the $ symbol in Regex represents the end of a line or string.

The following example shows how to use this syntax in practice.

Example: Use Where-Object to Filter for Strings that End With Pattern in PowerShell

Suppose we have a folder located at the following path:

  • c:/users/bobbi/data6

We can use the Get-ChildItem cmdlet to retrieve all files in this folder:

Suppose that we would like to filter the folder to only show the files that end with the string coaches.

We can use the following syntax to do so:

Get-ChildItem 'c:/users/bobbi/data6' | Where-Object { $_.Basename -match 'coaches$'}

The following screenshot shows how to use this syntax in practice:

PowerShell Where-Object ends with

Notice that this returns only the files that end with the string “coaches”:

  • assistant_coaches.txt
  • backup_coaches.txt
  • coaches.txt

Notice that this does not return the following file that contains but does not end with “coaches”:

  • coaches_backgrounds.txt

Note: We used $_.Basename to retrieve the base name of each file in the folder, which represents the file name without the extension.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Use Where-Object in List
PowerShell: How to Use Where-Object is Not Null
PowerShell: How to Use Where-Object with Multiple Conditions

Leave a Reply