使用power shell重命名文件名中包含括号的文件

时间:2012-06-10 17:30:31

标签: powershell powershell-v2.0

我正在尝试重命名文件名中包含括号的文件。这似乎不起作用,因为powershell将[]视为特殊字符,并且不知道该怎么做。

我的电脑上有一个文件夹c:\ test。我希望能够浏览该文件夹并重命名文件的所有文件或部分。以下代码似乎有效,但如果文件中包含任何特殊字符,代码将失败:

Function RenameFiles($FilesToRename,$OldName,$NewName){

    $FileListArray = @()
    Foreach($file in Get-ChildItem $FilesToRename -Force -Recurse  | Where-Object {$_.attributes -notlike "Directory"})
    {
        $FileListArray += ,@($file)
    }

    Foreach($File in $FileListArray)
    {
        IF ($File -match $OldName )
        {
            $File | rename-item -newName {$_ -replace "$OldName", "$NewName" }
        }
    }
}

renamefiles -FilesToRename "c:\test" -OldName "testt2bt" -NewName "test"

我确实找到了类似的问题:Replace square bracket using Powershell,但我无法理解如何使用答案,因为它只是解释错误的链接:

4 个答案:

答案 0 :(得分:9)

对于多个文件,可以使用一行完成。

要删除括号,请尝试:

get-childitem | ForEach-Object { Move-Item -LiteralPath $_.name $_.name.Replace("[","")}

答案 1 :(得分:7)

Move-Item -literalpath "D:\[Copy].log" -destination "D:\WithoutBracket.txt"

literalpath开关与Move-Item cmdlet一起使用[而不是使用rename-item cmdlet]

答案 2 :(得分:3)

就支架而言,您已经在旧版Technet Windows PowerShell Tip of the Week中获得了Microsoft官方回答。

您可以使用:

Get-ChildItem 'c:\test\``[*``].*'

答案 3 :(得分:2)

感谢您的帮助,大家帮助了很多,这是我在阅读完答案后最终提出的解决方案。

我的电脑上有一个名为c:\ test的文件夹,里面有一个名为“[abc] testfile [xas] .txt”的文件,我希望它被称为testfile2.txt

Function RenameFiles($FilesToRename,$OldName,$NewName){

$FileListArray = @()
Foreach($file in Get-ChildItem $FilesToRename -Force -Recurse  | Where-Object {$_.attributes -notlike "Directory"})
{
    $FileListArray += ,@($file.name,$file.fullname)
}

Foreach($File in $FileListArray)
{
    IF ($File -match $OldName )
    {
        $FileName = $File[0]
        $FilePath = $File[1]

        $SName = $File[0]  -replace "[^\w\.@-]", " "

        $SName = $SName -creplace '(?m)(?:[ \t]*(\.)|^[ \t]+)[ \t]*', '$1'

        $NewDestination = $FilePath.Substring(0,$FilePath.Length -$FileName.Length)
        $NewNameDestination = "$NewDestination$SName"
        $NewNameDestination | Write-Host

        Move-Item -LiteralPath $file[1] -Destination $NewNameDestination
        $NewNameDestination | rename-item -newName {$_ -replace "$OldName", "$NewName" }

        }
    }
}


renamefiles  -FilesToRename "c:\test" -OldName "testfile" -NewName "testfile2"
相关问题