PowerShell: Use Rename-Item and Overwrite if Filename Exists


You can use the Rename-Item cmdlet in PowerShell to rename a specific file.

However, if the new filename that you specify already exists then you will receive an error.

To rename a file and overwrite any existing file with the same name, you must instead use the Move-Item cmdlet with the -Force parameter as follows:

Get-Childitem team_info1.txt | ForEach-Object {
    Move-Item $_ $_.Name.Replace("team_info1", "team_info2") -Force
}

This particular example renames the file named team_info1.txt to team_info2.txt and overwrites any existing file already named team_info2.txt.

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

Example: How to Rename File and Overwrite if Filename Exists in PowerShell

Suppose that our current directory has the following path:

  • C:\Users\bobbi\data1

We can type Get-ChildItem to list out all files in this current directory:

Suppose that we would like to rename the file named team_info1.txt to team_info2.txt.

Suppose we attempt to use the Rename-Item cmdlet to do so:

Rename-Item "team_info1.txt" -NewName "team_info2.txt"

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

We receive an error because this filename already exists in the current directory.

To rename the file and overwrite the existing file with the same name, we can use the following syntax instead:

Get-Childitem team_info1.txt | ForEach-Object {
    Move-Item $_ $_.Name.Replace("team_info1", "team_info2") -Force
}

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

PowerShell Rename-Item overwrite

Notice that the file named team_info1.txt has been renamed to team_info2.txt and the existing filename with the same name has simply been overwritten.

Note: In this example we only renamed one file but you can use similar syntax to rename all files in a folder that match a particular pattern.

Related Tutorials

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

PowerShell: How to Rename File Extension of Multiple Files
PowerShell: How to Rename Multiple Folders
PowerShell: How to Copy and Rename a File

Leave a Reply