繁体   English   中英

有没有办法使用powershell以模式重命名文件夹中的文件?

[英]Is there a way to rename files in a folder in a pattern using powershell?

我的任务是使用某种模式重命名一堆文件/.tif。 文件夹中的文件顺序正确。 我必须遍历两个变量。 来自 AR 和 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)}

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

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

您的代码的问题在于,在创建新文件名的循环中,您没有对文件进行任何重命名,并且每次都覆盖相同的变量$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开关以实际开始重命名。

这应该可以解决问题:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM