How to Replace Part of Filename in PowerShell (With Example)


Often you may want to use PowerShell to replace a specific part of a filename in multiple files.

You can use the following syntax to do so:

Dir *.txt | Rename-Item -NewName {$_.name -replace "team","player"}

This particular example will replace the string team with player in all filenames that have a .txt extension in the current directory.

Any .txt files that do not contain the string team will remain unchanged.

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

Example: Use PowerShell to Replace Part of Filename

We can use the Dir command to first view all files in our current directory:

We can see that our current directory has four total files.

Suppose that we would like to replace the string team with player in each .txt file in the current directory.

We can use the following syntax to do so:

Dir *.txt | Rename-Item -NewName {$_.name -replace "team","player"}

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

PowerShell replace part of filename

Notice that when we use the Dir command again to view all of the files in the current directory that each .txt file that contained the string team has now been replaced with the string player instead.

The file named coaches_info.txt remained unchanged since it did not contain the string team in the filename.

Related Tutorials

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

PowerShell: How to Get File Name from Path
PowerShell: How to Add Date to File Name
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply