PowerShell与方括号

时间:2016-03-18 06:03:33

标签: powershell

所以,我已经阅读了很多关于使用Powershell重命名文件的Square Bracket []问题。这些帖子中的大多数都谈到删除括号。我需要保留括号,只需删除文件扩展名.crypted(CryptoLocker)。有400,000多个文件和172,000+个文件夹。我尝试了Move-Item cmdlet ......

Get-ChildItem c:\temp *.crypted | Move-Item -LiteralPath {$_.FullName.Replace(".crypted", "")} 

我收到错误Move-Item : Cannot move item because the item at 'C:\temp\Rule [1].txt' does not exist

您可能会看到新路径是正确的,但它表示它不存在。我很难过。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

为了解决方括号,请使用双引号``来解除它,

gci c:\temp\brackets *.crypted | % { 
  move-item $_.FullName.replace('[','``[') $_.FullName.Replace(".crypted", "")
}

需要加倍反引号才能传递反引号,而不会将其解释为括号中的转义字符。这有点乱,所以它看起来像Powershell中的一个错误或者非常令人惊讶的行为。

答案 1 :(得分:2)

调试提示:当您遇到代码问题并且正在使用管道时,请重写代码以不使用管道并将问题分解为步骤并插入调试辅助工具以帮助进行故障排除。可以是Write-Host,保存到临时变量等等。

对我来说,你写的Move-Item不起作用,我收到类似的错误信息。

以下是我作为解决方案所得到的内容:

Get-ChildItem *.crypted | ForEach-Object {Move-Item -LiteralPath $_.FullName $_.FullName.Replace('.crypted', '')}

请注意,我在Move-Item之后将2个参数传递给-LiteralPath,并且不需要任何反引号或任何异常。

以下是我展示问题的工作,以及我的解决方案。

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>
相关问题