[英]How do I recursively rename folders with Powershell?
使用 PS 递归重命名文件是微不足道的(来自Mike Ormond 博客的示例的变体):
dir *_t*.gif -recurse
| foreach { move-item -literal $_ $_.Name.Replace("_thumb[1]", "")}
我正在尝试递归重命名文件夹结构。
用例是我希望能够重命名整个 VS.NET 解决方案(例如,从 Foo.Bar 到 Bar.Foo)。 为此,有几个步骤:
我目前正在这个过程中迈出第一步。
我找到了这个帖子,它谈到了挑战,并声称有一个解决方案,但没有谈论那个解决方案是什么。
我一直碰到递归墙。 如果我让 PS 使用标志处理递归,则父文件夹会在子文件夹之前重命名,并且脚本会引发错误。 如果我尝试自己实现递归,我的头会很痛,而且 go 的事情严重错误——对于我的一生,我无法让事情在递归树的尾部开始重命名。
这是 rbellamy 最终得到的解决方案:
Get-ChildItem $Path -Recurse | %{$_.FullName} |
Sort-Object -Property Length -Descending |
% {
Write-Host $_
$Item = Get-Item $_
$PathRoot = $Item.FullName | Split-Path
$OldName = $Item.FullName | Split-Path -Leaf
$NewName = $OldName -replace $OldText, $NewText
$NewPath = $PathRoot | Join-Path -ChildPath $NewName
if (!$Item.PSIsContainer -and $Extension -contains $Item.Extension) {
(Get-Content $Item) | % {
#Write-Host $_
$_ -replace $OldText, $NewText
} | Set-Content $Item
}
if ($OldName.Contains($OldText)) {
Rename-Item -Path $Item.FullName -NewName $NewPath
}
}
怎么样 - 做一个全名的递归列表,按全名的长度降序排序,然后通过你的重命名例程运行它。
例如
gci <directory> -recurse |
foreach {$_.fullname} |
sort -length -desc
也许其中的某些东西很有用,这是一个递归并将“pre”添加到目录结构的片段
$dirs = Get-ChildItem c:/foldertorecurse -rec | Where-Object {$_.PSIsContainer -eq 1} | sort fullname -descending
foreach ( $dir in $dirs ) { rename-item -path $dir.fullname -newname ("pre" + $dir.name) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.