重命名项:Powershell 中的源路径和目标路径必须不同错误

2024-05-04

我正在使用 Powershell 并尝试返回目录的子项(恰好是子目录),然后使用Rename-Itemcmdlet 将子目录名称重命名为其他名称。

我觉得下面的代码应该有效:

Get-ChildItem "C:\Users\Admin\Desktop\mydirectory\subdirectory" | Rename-Item -NewName {$_.Name -replace 'test'} 

但我收到此错误:

Rename-Item : Source and destination path must be different.

我在这里缺少什么? 提前致谢!


既然你正在使用Get-ChildItem https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-childitem不限制结果files(通过-File开关),两个文件和目录可以在输出项中。

While Rename-Item https://learn.microsoft.com/powershell/module/microsoft.powershell.management/rename-item结果是安静无操作 if a file正在更名为一样的名字目前,在目录导致您看到的错误。

  • 这种令人惊讶的差异是GitHub 问题 #14903 https://github.com/PowerShell/PowerShell/issues/14903.

这适用于名称不符合的所有项目not包含子字符串'test',在这种情况下
-replace https://stackoverflow.com/a/40683667/45375操作按原样传递输入字符串。

如果您的目的是重命名仅文件,解决方案很简单add the -File switch:

Get-ChildItem -File "C:\Users\Admin\Desktop\mydirectory\subdirectory" |
  Rename-Item -NewName { $_.Name -replace 'test' } 

If 目录是(也)有针对性的,就像你的情况一样,你需要显式过滤掉不会发生实际重命名的输入项:

Get-ChildItem -Directory -Filter *test* "C:\Users\Admin\Desktop\mydirectory\subdirectory" |
  Rename-Item -NewName { $_.Name -replace 'test' } 

-Filter *test*确保只有包含该单词的子目录'test'是输出,这保证了实际的重命名发生(请注意,如果子目录entire名字是'test',因为这将使脚本块返回空字符串).


如果你只是想重命名一个single子目录到固定新名称,您根本不需要延迟绑定脚本块:

# NOTE: Works only if only a SINGLE subdirectory is returned.
Get-ChildItem -Directory "C:\Users\Admin\Desktop\mydirectory\subdirectory" |
  Rename-Item -NewName 'test'

如果你有multiple子目录并且您想要合并一个sequence编号到新名称中,您再次需要一个延迟绑定脚本块:

$num = 0
Get-ChildItem -Directory "C:\Users\Admin\Desktop\mydirectory\subdirectory" |
  Rename-Item -NewName { 'test' + ++(Get-Variable -Scope 1 num).Value } -WhatIf

这会将子目录重命名为test1, test2, ...
有关此技术的解释(需要Get-Variable https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-variable调用),参见这个答案 https://stackoverflow.com/a/53393980/45375.


如果你想preview重命名操作会发生这种情况,您可以添加-WhatIf通用参数 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_commonparameters#whatif to the Rename-Item调用,它将显示每个输入文件的内容would被重命名为.

然而,你必须infer从输出的情况来看当没有实际重命名时, 因为延迟绑定脚本块 https://stackoverflow.com/a/52807680/45375传递给-NewName返回和以前一样的名字.

例如,名为的输入文件foo would not改名,因为'foo' -replace 'test'回报'foo'未经修改,其中与-WhatIf将显示如下(为了便于阅读而添加换行符) - 请注意目标和目标路径是如何相同的:

What if: Performing the operation "Rename File" on target "
Item: C:\path\to\foo 
Destination: C:\path\to\foo
"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

重命名项:Powershell 中的源路径和目标路径必须不同错误 的相关文章

随机推荐