Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename it after copied using powershell

I am trying to recursively copy the files and rename them.

My folders has file with same name ,so i need to rename it the moment it is copied.

But i am keep facing issue. Following is my code. It should find the CopyForBuild.bat file and copy it to E:\CopyForBuild folder. Once it is copied , the first file should be Copyforbuild1.txt , the second one will be CopyforBuild2.txt and so on.

Following is my code. Where am i failing?

$File = Get-ChildItem -Path V:\MyFolder -Filter CopyForbuild.bat -Recurse

$i=1
Foreach ($f in $File)
{

   Copy-Item $f "E:\copyforbuild\"
   Rename-Item  -path "E:\Copyforbuild\"+"$f" -newname "CopyForbuild"+"$i"+".txt"
   $i = $i+1
}
like image 794
Samselvaprabu Avatar asked Dec 30 '11 10:12

Samselvaprabu


1 Answers

You can rename file while copying in Copy-Item, just provide full path in both places:

copy-item c:\PST\1.config c:\PST\2.config

This will rename 1.config to 2.config. No need to call separate rename function. Your code should now look something like this:

$File = Get-ChildItem -Path "V:\MyFolder\" -Filter CopyForbuild.bat -Recurse

$i=1
Foreach ($f in $File)
{
   Copy-Item $f.FullName ("E:\copyforbuild\" + $f.BaseName + $i +".txt")
   $i++
}

You can make it even shorter if use For loop:

$File = Get-ChildItem -Path "V:\MyFolder\" -Filter CopyForbuild.bat -Recurse

for($i = 0; $i -lt $File.Count; $i++)
{
   Copy-Item $File[$i].FullName ("E:\copyforbuild\" + $File[$i].BaseName + $i +".txt")
}

Or way shorter and wider if follow Richard's comment

like image 178
Andrey Marchuk Avatar answered Oct 24 '22 21:10

Andrey Marchuk