Monthly Archive

Categories

Rename files problem

I came across this interesting problem and thought it was worth a post.

Problem

You have a folder with a set of files with names like this

Black or Blue [15665782345].txt
Black or Green [1068682345].txt
Black or White [12345].txt
Black or Yellow [A2G345].txt
Blue or Green [14786862345].txt
Pink or Yellow [12345465785].txt
Purple or Gold [345612345].txt
Red or Blue [112132345].txt
Yellow or White [4335433678512345].txt

You need to rename each file so that the [] and stuff between them are removed.

Rename-Item won’t work because of the [].

Solution

001
002
003
004
005
006
Get-ChildItem | foreach {
  
    $name = $_.BaseName.split('`[')
    $newname = $name[0].TrimEnd(" ") + $_.Extension
    Move-Item -LiteralPath $_ -Destination $newname -Force
}

 

Read the file list with Get-ChildItem.  Create the new name by splitting the Basename at the “[“ character and Trim any trailing blanks. Add the extension back on.

Use Move-Item to move the file to the same folder with a new name.  The file is renamed.

I did try using the –split operator instead of split() but didn’t have any success

Technorati Tags: Powershell,files,rename

Leave a Reply