重命名文件和文件夹关键字-使用CSV查找文件 [英] Rename Files & Folders Keywords - Using a CSV Look Up File

查看:103
本文介绍了重命名文件和文件夹关键字-使用CSV查找文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据CSV文件中的关键字来重命名文件和文件夹.

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

CSV保存包含将组成文件和文件夹名称的搜索和替换关键字.

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

Search | Replace
Document | DTX
Processing | PRX
Implementation | IMX
...

  • 并非所有文件名都包含文件名中的每个单词.
  • 并非所有文件夹都会在文件夹名称中包含每个单词
  • Powershell必须搜索子项,即文件夹和文件 名称.
  • 如果找到单词(匹配)-用CSV代替
    • 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:

      使用Powershell递归重命名使用查找文件的目录

      powershell脚本来重命名目录中的所有文件

      http://code.adonline.id.au/batch-rename-文件/

      我只管理了以下代码段

      $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
      }
      

      一次只能替换一个.

      问题:

      如何使用CSV作为查找或参考文件来递归搜索和替换文件和文件夹名称.

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

      推荐答案

      当您需要按其他值查找值时,通常使用的转到数据结构是字典,或者在PowerShell术语中是哈希表.像这样将您的CSV读入字典:

      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
        }
      }
      

      这篇关于重命名文件和文件夹关键字-使用CSV查找文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆