Home » How to Use Get-ChildItem Filter with Regex in PowerShell

How to Use Get-ChildItem Filter with Regex in PowerShell

To use a regular expression (regex) filter with the Get-ChildItem cmdlet in PowerShell, you can use the Where-Object cmdlet to filter the output based on a regex pattern.

The following method shows how you can do it with syntax.

Method 1: Use Get-ChildItem with regex filter

Get-ChildItem | Where-Object { $_.Name -match '^syslog_\d{4}' }

This example will return the files that match the regex pattern.

The following example shows how you can use this method.

Use Get-ChildItem with Regex Filter in PowerShell

The following PowerShell syntax shows how you can do it.

# specify the folder path
$folderPath = "C:\temp\log"

# get the files that matches the regex pattern
Get-ChildItem -Path $folderPath | Where-Object { $_.Name -match '^syslog_\d{4}' }

Output:

PowerShell use Get-ChildItem with regex pattern
PowerShell use Get-ChildItem with regex pattern

In this script, we define a variable $folderPath that contains the directory path.

We then use the Get-ChildItem cmdlet to retrieve all files from the specified folder and pipe them to the Where-Object cmdlet.

The Where-Object command uses the regex pattern to filter the result based on the specified search criteria where the file name should start with syslog_ and contain numbers in it.

Finally, the list of files that match the specified regex patterns is displayed on the console.

Conclusion

I hope the above article on using the Get-ChildItem with regex filter in PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.