![为什么当我尝试重命名文件时,Powershell 会告诉我我的文件代表一个路径?](https://linux22.com/image/1525255/%E4%B8%BA%E4%BB%80%E4%B9%88%E5%BD%93%E6%88%91%E5%B0%9D%E8%AF%95%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6%E6%97%B6%EF%BC%8CPowershell%20%E4%BC%9A%E5%91%8A%E8%AF%89%E6%88%91%E6%88%91%E7%9A%84%E6%96%87%E4%BB%B6%E4%BB%A3%E8%A1%A8%E4%B8%80%E4%B8%AA%E8%B7%AF%E5%BE%84%EF%BC%9F.png)
我有一个文件名“+1.txt”,我想将其重命名为“+2.txt”
我的 Powershell 脚本是:
$old = "\+1"
$new = "\+2"
Get-ChildItem | Rename-Item -NewName {$_.name -replace $old, $new }
返回:
powershell : Rename-Item : Cannot rename the specified target, because it represents a path
我该如何纠正这个问题?
答案1
PowerShell 中的正确转义字符是 `(反勾)。
例如,您可以编写以下命令来获取带有换行符的字符串:
$newline = "`n"
此外,至少在测试中,我不需要对其进行转义。所以就可以Rename-Item "+1.txt" "+2.txt"
了。尝试使用-replace
需要在第一个参数中使用反斜杠,但不需要第二个参数。所以$new = "+2"
应该可以工作。原因是的第一个参数-replace
可能是正则表达式。因此该术语需要一个未经特殊处理的文字 +。第二个术语被处理为文字字符串,因此您不需要任何特殊的转义或类似操作。
答案2
-replace
使用正则表达式,但您不需要手动转义字符。Get
-ChildItem 迭代当前路径中的所有项目,您必须指定一个名称
$old = "+1.txt"
$new = "+2.txt"
Get-ChildItem $old -file|
Rename-Item -NewName {$_.FullName -replace [regex]::escape($old), $new }
或者使用仅限哪里的-match
模式。
$old = "+1.txt"
$new = "+2.txt"
Get-ChildItem |
where Name -match [regex]::escape($old)|
Rename-Item -NewName $new