Renaming a file that has a bracket in the file name using power shell

powershell, powershell-2.0

Solution

Thanks for help guys you all helped a lot this is the solution I came up with in the end after reading your reply’s .

I have a folder on my pc called c:\test and it has a file in it called "[abc] testfile [xas].txt" and i want it to be called 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"

Problem

I am trying to rename a file that has a bracket in the file name. This does not seem to work because powershell sees [] as special characters and does not know what to do. I have a folder on my computer c:\test. I want to be able to look through that folder and rename all files or portions of the file. The following code seems to work but if the file has any special characters in it the code fails: ``` 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" ``` I did find a similar question: Replace square bracket using Powershell, but I can't understand how to use the answer cause it's just a link explaining the bug:

Original source

Related problems