Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a single PowerShell command to copy and rename files?

Tags:

powershell

I am using the following command to copy files from a network share to my local hard drive based on a CSV file.

import-csv C:\TEST\test.csv | foreach {copy-item -path $_.npath -destination 'C:\TEST\'} 

The next step would be to then use a different CSV file to rename these files based on their current file name.

Is there a command that will allow me to copy and item and rename it as well?

like image 909
toolshed Avatar asked Jan 21 '13 03:01

toolshed


People also ask

How do I bulk Rename files in PowerShell?

What to Know. Open File Explorer, go to a file folder, select View > Details, select all files, select Home > Rename, enter a file name, and press Enter. In Windows PowerShell, go to a file folder, enter dir | rename-item -NewName {$_.name -replace “My”,”Our”} and press Enter.

How do I copy and replace a file in PowerShell?

By default, when you will copy item in PowerShell using the Copy-Item, it will overwrite the files in the destination folder. The above PowerShell script will overwrite the files but it will show an error for folders: Copy-Item : An item with the specified name D:\Bijay\Destination\Folder1 already exists.


1 Answers

If you have a CSV containing two columns, oldfilepath and newfilename, then you can use the following.

Import-Csv C:\test.csv | % { Copy-Item -Path $_.oldfilepath -Destination "C:\TEST\$($_.newfilename)" } 

Notice how the $_.newfilename is encapsulated inside a $(). That's because $_.newfilename is an expression (since we are getting a property out of the variable), and not a variable. $() tells PowerShell to solve the expression before using it in the string. If we don't use it, it would have used the whole csv-object for that row($_) as a string and returned an error.

like image 66
Frode F. Avatar answered Sep 29 '22 16:09

Frode F.