Rename Files & Folders Keywords - Using a CSV Look

2019-04-02 21:59发布

I would like to rename files and folders based on keywords found in a CSV file.

The CSV holds the search and replace keywords that will make up file and folder names.

Search | Replace
Document | DTX
Processing | PRX
Implementation | IMX
...
  • Not all the file names include each word in the file name.
  • Not all the folders will include each word in the folder name
  • Powershell will have to search the child item ie the folder and file names.
  • If it finds the word (match) - Substitute from the CSV

I have looked at these threads to help me:

Using Powershell to recursively rename directories using a lookup file

powershell script to rename all files in directory

http://code.adonline.id.au/batch-rename-files/

I have only managed below snippet

$folder = "C:\Folders"               #target folder containing files
$csv    = "C:\FileNameKeywords.csv"             #path to CSV file

cd ($folder);
Import-Csv ($csv) | foreach {
  Rename-Item -Path $_.Path -NewName $_.Filename
}

It only replaces one at a time.

Question:

How can I recursively search and replace in file and Folder Names using a CSV as a look up or reference file.

2条回答
贪生不怕死
2楼-- · 2019-04-02 22:25

When you have the need to look up values by other values the usual go-to data structure is a dictionary, or in PowerShell terms a hashtable. Read your CSV into a dictionary like this:

$keywords = @{}
Import-Csv $csv | ForEach-Object {
  $keywords[$_.Search] = $_.Replace
}

Then traverse your folder tree and build the new filenames by replacing each key with its respective value:

Get-ChildItem $folder -Recurse | ForEach-Object {
  $newname = $_.Name
  foreach ($word in $keywords.Keys) {
    $newname = $newname.Replace($word, $keywords[$word])
  }

  if ($_.Name -ne $newname) {
    Rename-Item -Path $_.FullName -NewName $newname
  }
}
查看更多
smile是对你的礼貌
3楼-- · 2019-04-02 22:38

ill give it a shot. I'm assuming search and replace are your headers in this scenario. this in addition to your $folder and $csv variables.

$csvobject=import-csv $csv 
Foreach($obj in $csvobject){ 
$search=$obj.search
$replace=$obj.replace
get-childitem path $folder |where{$_.name -like "$($obj.search)"} | rename-item -newname {$_.name -replace "$search", "$replace"} }

The replace handles regex so u will need to make sure Any special characters are properly escaped.

查看更多
登录 后发表回答