【问题标题】:Is there a way to rename files in a folder in a pattern using powershell?有没有办法使用powershell以模式重命名文件夹中的文件?
【发布时间】:2019-12-04 12:59:56
【问题描述】:

我的任务是使用某种模式重命名一堆文件/.tif。文件夹中的文件顺序正确。我必须遍历两个变量。从 A-R 和 1-20。它应该以“A01”开始,如果它击中“A20”,它应该移动到“B01”......等等。直到“R20”。

我创建了两个变量,称为字母和数字,并使用两个 for 循环遍历它们并打印它们。这工作得很好。之后我创建了另一个变量来存储它的结果。我坚持的任务是重命名部分。这是我目前使用的代码。

$letters = @("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R")
$numbers = @("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20")

for($i = 0; $i -lt $numbers.Length; $i++){
 for($j = 0; $j -lt $letters.Length; $j++){
    $Output = $letters[$j], $numbers[$i]
    $newFileName = $Output+".tif"
 }
}

在最后一行之后,我尝试了类似:

Dir | %{Rename-Item $_ -NewName ($newFileName)}

但这在任何变化中都失败了。

这里的下一步是什么/第一种方式可能吗? 提前致谢!

【问题讨论】:

    标签: powershell design-patterns rename


    【解决方案1】:

    您的代码的问题在于,在创建新文件名的循环中,您没有对文件进行任何操作来重命名自己,并且每次都覆盖相同的变量 $newFileName

    你可以这样做:

    $filePath = 'X:\tifs'  # put the path of the folder where the tif files are here
    $letters  = "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R"
    
    # initialize two counters
    $i = $j = 0
    Get-ChildItem -Path $filePath -Filter '*.tif' | ForEach-Object {
        $newFileName = '{0}{1:00}.tif' -f $letters[$i], $j++
        $_ | Rename-Item -NewName $newFileName -WhatIf
        if ($j -gt 20) {
            $i++    # go to the next letter
            $j = 0  # reset the number count
        }
        # if the letter counter has exceeded the number of letters, break out of the loop
        if ($i -gt $letters.Count) { break }
    }
    

    -WhatIf 开关首先用于测试。在控制台窗口中,您可以看到Rename-Item cmdlet 做什么。如果您对显示的内容感到满意,请移除 Whatif 开关以实际开始重命名。

    【讨论】:

    • 感谢您的回答。可悲的是,有些事情发生了变化(我必须从 A01 到 R01,然后再到 A02 等等),但我试图弄清楚这一点。我不想再打扰你了! - 唯一的问题是,在你的代码中,我改变了它,它以 1 开头,而不是 0。但仅此而已。
    • @FelixSchupp 对不起,误读了,从 0 开始。不过很容易修复。干得好
    【解决方案2】:

    这应该可以解决问题:

    $directory  = 'C:\directory\test'
    
    $files      = Get-ChildItem -Path $directory -Filter '*.tif'
    $char       = 65
    $counter    = 1
    
    foreach( $file in $files ) {
    
        $newFilename = [char]$char + ( "{0:00}" -f $counter)
    
        Move-Item -Path ($file.FullName) -Destination ($newFilename + $file.Extension) | Out-Null
    
        $char++
        $counter++
    
        if( $counter -gt 20 ) {
            $char++
            $counter = 1
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 2022-11-19
      • 1970-01-01
      相关资源
      最近更新 更多