我迷失了简单的重命名项目。需要将文件夹名称更改为“01”、“02”、“03”...尝试了所有方法,但最后我得到了“项目不存在”。抱歉问了个愚蠢的问题,但我一整天都在寻找解决方案。
PS C:\Users\admin>
$nr = 1
Dir E:"Data-test" | %{Rename-Item $_ -NewName (‘{0}’ -f $nr++)}
Rename-Item : Cannot rename because item at 'ert' does not exist.
At line:3 char:23
+ Dir E:"Data-test" | %{Rename-Item $_ -NewName (‘{0}’ -f $nr++)}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
Rename-Item : Cannot rename because item at 'ukh' does not exist.
At line:3 char:23
+ Dir E:"Data-test" | %{Rename-Item $_ -NewName (‘{0}’ -f $nr++)}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
Rename-Item : Cannot rename because item at 'yph' does not exist.
At line:3 char:23
+ Dir E:"Data-test" | %{Rename-Item $_ -NewName (‘{0}’ -f $nr++)}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
user14915444 的有用答案 https://stackoverflow.com/a/65513163/45375提供了关键的指针:
问题是Windows PowerShell情境串连Get-ChildItem
(dir
) 按文件输出对象name而不是通过完整路径,需要使用$_.FullName
而不仅仅是$_
; the 问题已解决PowerShell [核心] v6.1+ - see 这个答案 https://stackoverflow.com/a/53400031/45375了解详情。
但是,在您的情况下,通过管道可以完全避免该问题Get-ChildItem
output directly to Rename-Item
, 用一个延迟绑定脚本块 https://stackoverflow.com/a/52807680/45375,这也加快了操作速度:
[ref] $nr = 1
Get-ChildItem E:Data-test | Rename-Item -NewName { '{0}' -f $nr.Value++ } -WhatIf
Note: The -WhatIf common parameter https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_commonparameters#whatif in the command above previews the operation. Remove -WhatIf
once you're sure the operation will do what you want.
请注意使用[ref] https://learn.microsoft.com/en-US/dotnet/api/System.Management.Automation.PSReference变量,它允许从延迟绑定脚本块内部增加输入对象的序列号。这是必要的,因为延迟绑定脚本块在child调用者范围的范围 - 与传递给的脚本块不同ForEach-Object https://learn.microsoft.com/powershell/module/microsoft.powershell.core/foreach-object (%
) and Where-Object https://learn.microsoft.com/powershell/module/microsoft.powershell.core/where-object (?
).
See GitHub 问题 #7157 https://github.com/PowerShell/PowerShell/issues/7157来讨论这个差异。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)