I'm using this answer to try to copy files to a new location using a .csv list where OldName is the current file name and NewName is the new name including filepath. What is the best way to force the script to generate a new folder according to the new path?
For example:
OldName NewName
A.pdf C:\NewFolder\Anew.pdf
This is my script
$Copies = Import-Csv '.\copies.csv' -Header "OldName","NewName"
foreach($File in $Copies) {
New-Item -Force $File.NewName -Type File
Copy-Item $File.OldName $File.NewName
}
But this overwrites any files that stay in the same folder before they get copied.
Replace the line where you create the directory:
New-Item -Force $File.NewName -Type File
With this:
$NewDir = ($File.NewName -as [System.IO.FileInfo]).DirectoryName
If (-not (Test-Path -Path $NewDir)) {
New-Item -ItemType Directory -Path $NewDir -Force | Out-Null
}