PowerShell: How to Copy and Rename a File


You can use the following method to copy and rename files in PowerShell:

Method 1: Copy and Rename One File to New Folder

Copy-Item "c:\original\my_data.txt" "c:\new\my_data_modified.txt"

This particular example copies the file named my_data.txt from the folder named original and pastes it into the folder named new and renames it my_data_modified.txt.

The original file is kept in the original folder.

Method 2: Copy and Rename Multiple Files in Existing Folder

$path = "c:\users\bobbi\data1"

Get-ChildItem -Path $path -File | ForEach-Object {
    Copy-Item -Path $_.FullName -Destination "$($_.FullName).csv"
}

This particular example creates a copy of each of the files in the folder named data1 and renames them all with a .csv extension at the end.

All original files are kept in the folder as well.

The following examples show how to use each method in practice.

Example 1: Copy and Rename One File to New Folder Using PowerShell

Suppose that our current directory has the following path:

  • C:\Users\bobbi\data1

We can type Dir to list out all files in this current directory:

Suppose that we would like to copy the file named teams1.txt to a new folder named data2 and rename it teams1_modified.txt.

We can use the following syntax to do so:

Copy-Item "c:\users\bobbi\data1\teams1.txt" "c:\users\bobbi\data2\teams1_modified.txt" 

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

PowerShell copy and rename file

We can see that we were able to successfully copy the file named teams1.txt into the folder named data2 and rename it teams1_modified.txt.

Example 2: Copy and Rename Multiple Files in Existing Folder Using PowerShell

Once again, suppose that our current directory has the following path:

  • C:\Users\bobbi\data1

We can type Dir to list out all files in this current directory:

Suppose that we would like to make a copy of each of the files in this folder and add a .csv extension to each file name.

We can use the following syntax to do so:

$path = "c:\users\bobbi\data1"

Get-ChildItem -Path $path -File | ForEach-Object {
    Copy-Item -Path $_.FullName -Destination "$($_.FullName).csv"
}

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

PowerShell copy and rename multiple files in folder

We can see that we were able to successfully make a copy of each of the files in this folder and add a .csv extension to each file name.

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 List Files in Directory by Date
PowerShell: How to Replace Every Occurrence of String in File

Leave a Reply