是否有方法使用powershell以模式重命名文件夹中的文件?
我的任务是使用某种模式重命名一堆文件/.tif。文件夹中的文件顺序正确。我必须迭代两个变量。从A-R和1-20。它应该以“A01”开始,如果它点击“A20”,它应该移动到“B01”。。等等直到“R20” 我创建了两个名为字母和数字的变量,并使用两个for循环遍历它们并打印它们。这很有效。之后,我创建了另一个变量来存储结果。我的任务是重命名部分。这就是我目前使用的代码是否有方法使用powershell以模式重命名文件夹中的文件?,powershell,design-patterns,rename,Powershell,Design Patterns,Rename,我的任务是使用某种模式重命名一堆文件/.tif。文件夹中的文件顺序正确。我必须迭代两个变量。从A-R和1-20。它应该以“A01”开始,如果它点击“A20”,它应该移动到“B01”。。等等直到“R20” 我创建了两个名为字母和数字的变量,并使用两个for循环遍历它们并打印它们。这很有效。之后,我创建了另一个变量来存储结果。我的任务是重命名部分。这就是我目前使用的代码 $letters = @("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K
$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
}
}
谢谢你的回答。可悲的是,有些事情发生了变化(我必须从A01到R01,然后再到A02等等),但我试图弄清楚这一点。我不想再打扰你了唯一的问题是,在您的代码中,我更改了它,它以1开头,而不是以0开头。费利克斯楚普:对不起,误读了,从0开始。不过很容易解决。做得好