I have a script which renames files taken from a CSV but it throws an error when it trys to re-rename files after it has already carried out the successful proceedure
CSV file is like:
old new
AC100 DC100
AC101 DC102
Code tried:
$sourceDir = read-host "Please enter source Dir:"
$csvL = $sourceDir + "\files.csv"
$csv = import-csv $csvL
$files = get-childitem $sourceDir
$csv | % {
ForEach( $file in $files){
if($file = $_.old){
$old = $sourceDir + "\" + $_.old
Rename-Item $old $_.new
}
}
}
I beleive it is something to do with looping and the csv but im not sure where im going wrong, i have had similar issue before.
Here is a sample of the error.
+ Rename-Item <<<< $old $_.new
Rename-Item : Cannot rename because item at 'C:\scripts\2039X.67438.TXT' does not exist.
At C:\scripts\renamerTim.ps1:18 char:15
+ Rename-Item <<<< $old $_.new
Rename-Item : Cannot rename because item at 'C:\scripts\2039X.67438.TXT' does not exist.
At C:\scripts\renamerTim.ps1:18 char:15
+ Rename-Item <<<< $old $_.new
Rename-Item : Cannot rename because item at 'C:\scripts\2039X.67438.TXT' does not exist.
At C:\scripts\renamerTim.ps1:18 char:15
+ Rename-Item <<<< $old $_.new
Rename-Item : Cannot rename because item at 'C:\scripts\2039X.67438.TXT' does not exist.
At C:\scripts\renamerTim.ps1:18 char:15
+ Rename-Item <<<< $old $_.new
Rename-Item : Cannot rename because item at 'C:\scripts\2039X.67438.TXT' does not exist.
At C:\scripts\renamerTim.ps1:18 char:15
+ Rename-Item <<<< $old $_.new
Rename-Item : Cannot rename because item at 'C:\scripts\2039X.67438.TXT' does not exist.
At C:\scripts\renamerTim.ps1:18 char:15
+ Rename-Item <<<< $old $_.new
Rename-Item : Cannot rename because item at 'C:\scripts\2039X.67438.TXT' does not exist.
At C:\scripts\renamerTim.ps1:18 char:15
+ Rename-Item <<<< $old $_.new
thanks in advance, Craig
I think the
ForEach( $file in $files)
is redundant, since you already traverse each "file" with the$csv | % {
command. I'd try something like:You have a redundant nested loop.
$csv | %{ ... }
will already loop through file in the csv, and then the foreach loops through each file in the folder.Try this: