簡體   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