PowerShell: Use Move-Item and Overwrite Existing File


By default, when you use the Move-Item cmdlet in PowerShell to move a file from one folder to another, an existing file with the same name will not be overwritten.

However, you can use the -Force parameter to overwrite an existing file with the same name.

You can use the following syntax to do so:

Move-item -Path 'c:\source\data.txt' -destination 'c:\dest\data.txt' -Force

This particular example moves the file named data.txt from a folder named source to a folder named dest.

If a file named data.txt already exists in the dest folder, then it will be overwritten.

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

Example: Use Move-Item and Overwrite Existing File in PowerShell

Suppose we have a text file saved in the following location:

  • c:\users\bobbi\data1\coaches.txt

Suppose that we would like to move this coaches.txt file to a new folder with the following location:

  • c:\users\bobbi\data2\coaches.txt

We can use the Dir statement to view the files in each of these folders:

We can see that a file named coaches.txt already exists in the data2 folder.

Suppose we attempt to use the Move-Item cmdlet to move the coaches.txt file from the data1 to data2 folder:

Move-item -Path 'c:\users\bobbi\data1\coaches.txt' -destination 'c:\users\bobbi\data2\coaches.txt'

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

Since we didn’t add the -Force parameter, we receive a message that tells us this file already exists in this folder.

To force PowerShell to overwrite the existing file, we can use the -Force parameter:

Move-item -Path 'c:\users\bobbi\data1\coaches.txt' -destination 'c:\users\bobbi\data2\coaches.txt' -Force

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

PowerShell move-item overwrite existing file

Notice that we don’t receive any error message this time.

We can use the Dir statement to view the contents of both folders once again:

We can see that the coaches.txt file no longer exists in the data1 folder and that it has instead been moved to the data2 folder and has overwritten the existing file with the same name.

Related Tutorials

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

PowerShell: How to Copy and Rename a File
PowerShell: How to Rename File Extension of Multiple Files
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply