Powershell重命名项无法重命名 [英] powershell Rename-Item fail to rename
问题描述
我的powershell脚本:
My powershell script:
$dst = 'C:\Temp'
#Get all folders in $dst
$folders = Get-ChildItem $dst | ?{ $_.PSIsContainer }
foreach($folder in $folders)
{
$cnt = (Get-ChildItem -filter *.txt $folder | Measure-Object).Count
$base = ($folder.FullName -split " \[.*\]$")[0]
$newname = $("{0} [{1}]" -f $base,$cnt)
Write-Host $folder.FullName "->" $newname
Rename-Item $folder.FullName $newname
}
问题
在我的第一次跑步中,我得到了:
On my first run I get this:
PS C:\Temp> C:\Temp\RenameFolders.ps1
C:\Temp\m1 -> C:\Temp\m1 [1]
在第二次跑步中,我得到了:
On my second run I get this:
PS C:\Temp> C:\Temp\RenameFolders.ps1
C:\Temp\m1 [1] -> C:\Temp\m1 [0]
Rename-Item : Cannot rename because item at 'C:\Temp\m1 [1]' does not exist.
At C:\Temp\RenameFolders.ps1:15 char:5
+ Rename-Item $folder.FullName $newname
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
我知道问题出在'['和']',但我真的不明白为什么.
I know that the problem is in '[' and ']', but I realy can't understand why.
有人可以向我解释为什么这是个问题吗?
Can someone explain me why is that a problem?
推荐答案
如果您正在运行PS 3+,请添加 -LiteralPath 开关以重命名:
If you are running PS 3+ add -LiteralPath switch to your rename:
Rename-Item -LiteralPath $folder.FullName $newname
否则使用Move-Item
Move-Item -LiteralPath $folder.FullName $newname
Powershell不喜欢文件名中的方括号,更多内容请参见以下
Powershell doesn't like square brackets in filenames, more in the following post:
当V2将方括号添加到通配符集以支持"blobing"时,这成为一个问题.
This became an issue with V2 when they added the square brackets to the wildcard character set to support "blobbing".
来自get-help about_wildcards
:
Windows PowerShell支持以下通配符.
Windows PowerShell supports the following wildcard characters.
通配符描述示例匹配项不匹配
Wildcard Description Example Match No match
-
匹配0或a * A,ag,Apple香蕉 更多字符
Matches zero or a* A, ag, Apple banana more characters
?完全匹配?一次 一个字符 指定的 位置
? Matches exactly ?n an, in, on ran one character in the specified position
[]匹配范围[a-l]看书,做饭,看 字符
[ ] Matches a range [a-l]ook book, cook, look took of characters
[]匹配指定的[bc]钩书,厨师钩 字符
[ ] Matches specified [bc]ook book, cook hook characters
[
和]
是特殊字符.
这篇关于Powershell重命名项无法重命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!