Powershell - find file by 'file name' and rename based on CSV

限于喜欢 提交于 2021-01-28 21:10:58

问题


I have a set of files (OldName) in a Windows directory that I would like to rename (NewName) based on the following CSV file:

OldName,NewName
Sources/texas play_PGC_Cpgc_entryPoint_Cbp_1.f4v,01 Texas Play.f4v
Sources/texas play_PGC_Cpgc_entryPoint_Dbp_1.f4v,02 First Song.f4v
Sources/texas play_PGC_Cpgc_entryPoint_Ebp_1.f4v,03 Yellow Rose.f4v

I'm not sure how to loop thru the CSV file... finding each file and replacing.

Any thoughts would be appreciated.


回答1:


First Import Your CSV file into powershell

$AnyVariableName = Import-Csv "$env:USERPROFILE:\Desktop\directoryname.txt"

Note: In my example, the path to the CSV file is on my desktop, but it may be different in yours.

Then use a foreach loop rename the items

foreach ($objName in $AnyVariableName){

  Rename-Item $objName.OldName $objName.NewName

}



回答2:


One way to do it is to create two lists and loop though each of them. The CSV file will be a reference list, so we'll grab the contents and convert it from CSV then store it in a variable

$CSVRef = Get-Content "C:\Path\To\CSV.csv" | ConvertFrom-CSV

Then we'll get the list of files who's names you want to change, and loop through each file. From inside the loop you can run another loop to find the current name in your reference list, and then change it to the new name.

Get-ChildItem "C:\path\to\f4v\files" -Filter *.f4v | ForEach-Object {

    #Grab the current item in a variable to access it within the second loop
    $CurrentFile = $_

    $CSVRef | ForEach-Object {

        if ($CurrentFile.Name -ilike $_.OldName) {

            Rename-Item $CurrentFile.FullPath $_.NewName        
        }
    }
}

So during the second loop we try to compare the file name with every "OldName" item in the CSV file list. If the OldName matches somewhere in the current file we're looping through then we run Rename-Item and provide it the NewName. It should automatically rename the file.




回答3:


Combining both examples works great

$CSVRef = Import-Csv "C:\Temp\Filename.txt"

Get-ChildItem "C:\Temp\FileFolder" -Filter *.pdf | ForEach-Object {
    $CurrentFile = $_
    ForEach ($objName in $CSVRef) {
            if ($CurrentFile.Name -ilike $objName.OLDNAME) {
                    Rename-Item $CurrentFile.FullName $objName.NEWNAME
                }
        }
}


来源:https://stackoverflow.com/questions/34287924/powershell-find-file-by-file-name-and-rename-based-on-csv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!