Search code examples
powershellrenamefilenamesbrackets

Handling brackets in filenames and foldernames in PowerShell


I have a folder E:\Tjuven with several folders starting with Andreas and containing [ and ].

In all those folders I have 2 files that I want to rename to the name of their folder. These files ALSO include [ and ] in the name.

So I wrote this:

$folderslist = Get-ChildItem -Path E:\Tjuven -Filter Andreas*
$folders = $folderslist.Name
ForEach ($folder in $folders) {
    $fillista = Get-ChildItem -Path E:\Tjuven\$folder
    $filer = $fillista.Name
    ForEach ($fil in $filer) {
        $filslut = $fil.Substring($fil.Length-3)
        Rename-Item "E:\Tjuven\$folder\$fil" "E:\Tjuven\$folder\$folder.$filslut"
    }
}

This works perfectly when the folders do not have [ or ] in them.

I know I can use literalpath for looking up folders etc, but I can't seem to figure out how to deal with that data when scripting actions on multiple files or folders with special characters [ and ] in them.

Anyone got any ideas how to make this work? If I can write this script in a smoother way, feel free to give me tips as well.


Solution

  • Get-ChildItem and Rename-Item use square brackets as wildcard characters. Use -LiteralPath instead of -Path:

    $root = "F:\test"    
    Get-ChildItem -Path $root | % {
        $dirName = $_.Name
        $files = Get-ChildItem -LiteralPath $_.FullName
        $files | % {
            Rename-Item -LiteralPath $_.FullName -NewName "$dirName$($_.Extension)"
        }
    }
    

    Explanation here