【问题标题】:Rename Part of File Name重命名文件名的一部分
【发布时间】:2020-01-29 05:34:18
【问题描述】:

我希望使用 csv 文件批量重命名 pdf 文件的一部分。我有一个包含两列名称和新名称的 csv 文件。我的 pdf 文件的命名约定为 222222_test(例如),位于 C:\TEST 文件夹中。在 csv 文件中,222222 在 name 列中,而 Jonathan 在 Newname 列中。
只要我可以让它工作,这个文件夹就会有数百个 pdf 文档。

$csv    = Import-Csv "C:\TEST\Book1.csv"

# location of your files
$files = get-childitem "C:\TEST\*.DOCX"


foreach($item in $CSV){
foreach($file in $files){
    if($item.name -eq $file.basename){
        rename-item $file.fullname -NewName         "$($item.newname)$($file.extension)" -Verbose
        }
    }
}

我正在寻找一种将 222222(仅)更改为 Jonathan 的方法,以便 pdf 文件为 Jonathan_test。当文件名只有 222222 时,我可以使用代码,但是当 pdf 为 222222_test 时,代码不起作用。

【问题讨论】:

  • 能否请您从您的 CSV 文件中发布几行以及匹配文件的前/后名称?我是那些在没有一些例子的情况下思考这个问题的人之一...... [grin]

标签: powershell rename


【解决方案1】:

试一试,如果 WhatIf 适用于您的文件,请删除它。否则,我们需要从 csv 中查看一些示例数据。

foreach ($item in $CSV) {
    foreach ($file in $files) {
        if ($item.name -eq $file.basename) {
            Rename-Item $file.fullname -NewName $($file.FullName -replace $item.name, $item.newname) -WhatIf
        }
    }
}

【讨论】:

  • 你说得对,这取决于 CSV 文件中的真实内容。
【解决方案2】:

对于数百个 CSV 行,预先构建一个 hashtable 将旧名称映射到新名称是值得的。

然后您只需在文件名上循环一次,在每次迭代中执行快速哈希表查找。

# Initialize the hashtable.
$ht = @{}

# Fill the hashtable, with the "name" column's values as the keys,
# and the "newname" columns as the values.
Import-Csv C:\TEST\Book1.csv | 
  ForEach-Object {
    $ht.Add($_.name, $_.newname)
  }


# Loop over the files and rename them based on the hashtable
Get-ChildItem C:\TEST\*.DOCX | Rename-Item -NewName {
  $prefix = ($_.BaseName -split '_')[0] # Get prefix (before "_")
  $newPrefix = $ht[$prefix] # Look up the prefix in the hashtable.
  if ($newPrefix) { # Replace the prefix, if a match was found.
    $newPrefix + $_.Name.Substring($prefix.Length)
  }
  else { # No replacement - output the original name, which is a no-op.
    $_.Name 
  }
} -WhatIf

-WhatIf预览重命名操作;删除它以执行实际重命名。

【讨论】:

  • 我很高兴听到这个消息,@JonathanSinger;我的荣幸。请允许我在下一条评论中给你标准的建议给新人。
  • 如果某个答案解决了您的问题,请点击旁边的大复选标记 (✓) 接受它,并可选择对其进行投票(投票至少需要 15 个声望点)。如果您发现其他答案有帮助,请给他们投票。接受(您将获得 2 个声望点)和投票可以帮助未来的读者。请参阅this article 了解更多信息。如果您的问题尚未得到完全解答,请提供反馈或self-answer
猜你喜欢
  • 2010-11-26
  • 2011-12-03
  • 1970-01-01
  • 2011-12-01
  • 2018-12-31
  • 1970-01-01
  • 2013-12-05
  • 2020-06-04
  • 1970-01-01
相关资源
最近更新 更多