powershellmultidimensional-arrayrename-item-cmdlet

Renaming Specific Files in various folders with Import-Csv


I’m attempting to rename a bunch of files that are located in multiple folders. The filenames are not unique because they live in multiple directories. Hence, I'd like to fetch all specific files based on their path and then use the Rename-Item cmdlet to make them unique.

I'm using the Import-Csv cmdlet because I have the Paths and New File Names in a text file (headers are oldPath and NewFileName respectively).

I've got this so far:

    $documentList = @(Import-Csv -Path 'C:\Users\Desktop\testFolder\fileWithPathAndNewFileName.txt') 

$Paths = (ForEach-Object {

    (Gci -Path $documentList.oldPath)  

})  

$Paths | ForEach-Object {Rename-Item -Path $_.FullName -NewName "$($documentlist.newFileName)"}

Unfortunately, this isn't really working, but feels like it's almost there. I think where I'm screwing up is the -NewName parameter. I'm just not sure how to populate the NewFileName object from my text file correctly. Any help would be much appreciated. I apologize in advance if this seems somewhat trivial, I unfortunately haven't been consistent with my Powershell.


Solution

  • Your code is a little confused. ;-) ... if you have CSV file you should name it *.csv. If I got you right this should be enough actually:

    $documentList = Import-Csv -Path 'C:\Users\Desktop\testFolder\fileWithPathAndNewFileName.txt'
    
    foreach ($document in $documentList) {
        Rename-Item -Path $document.oldPath -NewName $document.NewFileName
    }
    

    You iterate over each row in your CSV file and use the value in the cells as input for the Rename-Item cmdlet. You need to have the complete path including filename to the file in the column "oldPath" and the NewName in the column "NewName"