如何使用Powershell递归重命名文件夹? [英] How do I recursively rename folders with Powershell?
问题描述
使用PS进行递归重命名很简单(例如迈克·奥蒙德的博客):
Recursive renaming files using PS is trivial (variation on example from Mike Ormond's blog):
dir *_t*.gif -recurse
| foreach { move-item -literal $_ $_.Name.Replace("_thumb[1]", "")}
我正在尝试递归重命名文件夹结构.
I'm trying to recursively rename a folder structure.
用例是我希望能够重命名整个VS.NET解决方案(例如,从Foo.Bar更改为Bar.Foo).为此,需要执行几个步骤:
The use case is I'd like to be able to rename a whole VS.NET Solution (e.g. from Foo.Bar to Bar.Foo). To do this there are several steps:
- 重命名文件夹(例如\ Foo.Bar \ Foo.Bar.Model => \ Bar.Foo \ Bar.Foo.Model)
- 重命名文件(例如Foo.Bar.Model.csproj => Bar.Foo.Model.csproj)
- 在文件内查找和替换以更正名称空间更改(例如'namespace Foo.Bar'=>'namespace Bar.Foo')
我目前正在此过程的第一步.
I'm currently working the first step in this process.
我发现此帖子,其中谈到了挑战,并提出了解决方案,但没有讨论该解决方案是什么.
I found this posting, which talks about the challenges, and claims a solution but doesn't talk about what that solution is.
我一直碰到递归墙.如果我让PS使用标志来处理递归,则父文件夹将在子文件夹之前重命名,并且脚本会引发错误.如果我尝试自己实施递归,那么我的头会很疼,而且事情会变得非常糟糕-在我的生命中,我无法让事物在递归树的尾部开始其重命名.
I keep running into the recursion wall. If I let PS deal with the recursion using a flag, the parent folder gets renamed before the children, and the script throws an error. If I try to implement the recursion myself, my head get's all achy and things go horribly wrong - for the life of me I cannot get things to start their renames at the tail of the recursion tree.
推荐答案
rbellamy最终得到的解决方案是:
Here's the solution rbellamy ended up with:
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
}
}
这篇关于如何使用Powershell递归重命名文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!