PowerShell: How to Use Test-Path with Wildcard Characters


You can use the Test-Path cmdlet in PowerShell to check if a particular folder or file exists at a specific path.

You can use wildcard characters ( * ) with the Test-Path cmdlet to check if a particular folder or file exists whose name contains a partial pattern.

For example, you can use the following syntax to check if any file exists in a particular location that contains the pattern “teams” anywhere in the file name:

Test-Path c:\users\bobbi\data2\*teams* -PathType leaf

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

Example: How to Use Test-Path with Wildcard Characters in PowerShell

Suppose that we are interested in searching through files in the following directory on our computer:

  • c:/users/bobbi/data2

We can use the following syntax to list out all files that exist in this directory:

Get-ChildItem c:\users\bobbi\data2

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

PowerShell Test-Path with wildcard

Suppose that we would like to check if there are any files in this directory that contain “team” anywhere in the file name.

We can use the Test-Path cmdlet with the following syntax to do so:

Test-Path c:\users\bobbi\data2\*teams* -PathType leaf

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

PowerShell Test-Path with wildcard

This returns True, which tells us that there is at least one file in this directory that contains the string “teams” in the file name.

Note that we could place a wildcard character on just one side of a string to check if a file starts or ends with a particular string.

For example, we could use the following syntax to check if there are any files in the directory that start with the string “teams”:

Test-Path c:\users\bobbi\data2\teams* -PathType leaf

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

PowerShell Test-Path wildcard starts with string

This returns True, which tells us that there is at least one file in this directory that starts with the string “teams” in the file name.

We could also use the following syntax to check if there are any files in the directory that end with the string “teams.txt”:

Test-Path c:\users\bobbi\data2\*teams.txt -PathType leaf

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

PowerShell Test-Path wildcard file ends with pattern

This returns False, which tells us that there are no files in this directory that end with the string “teams.txt” in the file name.

Note: You can find the complete documentation for the Test-Path cmdlet in PowerShell here.

Related Tutorials

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

PowerShell: How to Check if Folder Exists
PowerShell: How to Delete File if it Exists
PowerShell: How to Find Empty Folders

Leave a Reply