方括号内的PowerShell
因此,我读了很多关于使用Powershell重命名文件时方括号[]问题的文章。这些帖子中的大多数都谈到了去掉括号。我需要保留括号,只需删除文件扩展名方括号内的PowerShell,powershell,Powershell,因此,我读了很多关于使用Powershell重命名文件时方括号[]问题的文章。这些帖子中的大多数都谈到了去掉括号。我需要保留括号,只需删除文件扩展名.crypted(CryptoLocker)。有400000多个文件和172000多个文件夹。我尝试了Move-Item cmdlet Get-ChildItem c:\temp *.crypted | Move-Item -LiteralPath {$_.FullName.Replace(".crypted", "")} 我收到一个错误移动项目
.crypted(CryptoLocker)
。有400000多个文件和172000多个文件夹。我尝试了Move-Item cmdlet
Get-ChildItem c:\temp *.crypted | Move-Item -LiteralPath {$_.FullName.Replace(".crypted", "")}
我收到一个错误移动项目:无法移动项目,因为“C:\temp\Rule[1].txt”处的项目不存在
正如你可能看到的那样,新路径是正确的,但它说它不存在。我被难住了。如果有任何帮助,我们将不胜感激。为了解决括号问题,请使用双反勾号
`
将其转义,如下所示:
gci c:\temp\brackets *.crypted | % {
move-item $_.FullName.replace('[','``[') $_.FullName.Replace(".crypted", "")
}
需要将反勾号加倍,以便传递反勾号,而不是将其解释为括号中的转义字符。这有点混乱,因此看起来像是Powershell中的一个bug或是一个非常令人惊讶的行为。调试提示:当您遇到代码问题并且正在使用管道时,请重写代码以不使用管道,并将问题分解为多个步骤,插入调试辅助工具以帮助进行故障排除。可以是写入主机、保存到临时变量等
对我来说,你写的移动项目不起作用,我收到一条类似的错误消息
以下是我得出的解决方案:
Get-ChildItem *.crypted | ForEach-Object {Move-Item -LiteralPath $_.FullName $_.FullName.Replace('.crypted', '')}
请注意,在-LiteralPath
之后,我将两个参数传递给Move Item
,并且不需要反勾号或任何异常情况
以下是我的工作,以演示问题和我的解决方案。
D:\test\move> dir
Directory: D:\test\move
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 3/17/2016 9:21 PM 100347 file [1].pdf
D:\test\move> Get-ChildItem *.pdf | Move-Item -LiteralPath {$_.FullName.Replace('1', '2')}
Move-Item : Cannot move item because the item at 'D:\test\move\file [2].pdf' does not exist.
At line:1 char:23
+ ... ldItem *.pdf | Move-Item -LiteralPath {$_.FullName.Replace('1', '2')}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Move-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.MoveItemCommand
D:\test\move> Get-ChildItem *.pdf | ForEach-Object {Move-Item -LiteralPath $_.FullName $_.FullName.Replace('1', '2')}
D:\test\move> dir
Directory: D:\test\move
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 3/17/2016 9:21 PM 100347 file [2].pdf
也在扩展上工作
D:\test\move> dir
Directory: D:\test\move
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 3/17/2016 9:21 PM 100347 file [2].txt.crypted
D:\test\move> Get-ChildItem *.crypted | ForEach-Object {Move-Item -LiteralPath $_.FullName $_.FullName.Replace('.crypted', '')}
D:\test\move> dir
Directory: D:\test\move
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 3/17/2016 9:21 PM 100347 file [2].txt
D:\test\move>
您是否尝试了
重命名项
cmdlet?@jisaak该重命名项
cmdlet因括号和缺少-LiteralPath
而失败。这就是切换到-移动项目的最初需要。[]是PowerShell内部的通配符如果使用-LiteralPath
,则不需要使用反勾号,并且可以避免编写混乱的代码。我还说明了OPs原始命令出错的原因。@vonPryz此解决方案也有效。也谢谢你的帮助。虽然-LiteralPath
选项是一种更为简洁的方式,但我也可以看到将来可以使用它,非常感谢您的帮助。这就是解决方案。我很想使用ForEach对象
,但我也错过了一些东西。我感谢你的帮助和额外的指导。这是一个经过彻底测试的答案,在我的情况下,我没有遇到任何问题。