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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With