Search code examples
powershellpowershell-2.0reversebatch-rename

Parse and Switch Elements of Folder Names with Powershell 2.0


I have been trying to write a powershell script (my first) to

  1. parse out only the folders within a directory
  2. select only those folders matching a specific naming convention ('SEASON YEAR')
  3. switch the order of the elements of the name ('YEAR SEASON')

I eventually used the program BulkRenameUtility to do this using the regexp ^(\w+) (\d+) and switching the token order to $2 $1 -- however, I still am learning Powershell and would like to be able to do this without using an external program.

So, to re-iterate, at C:\Users\Test

there are folders and files.. some of the folders are named Spring 2015, Fall 2014, for example. However, other folders have names such as geogex. Files have names such as ENG1A SPRING 2015.odtand untitled_0.odt.

How do I only change the names of the folders named like "Spring 2015" to read "2015 Spring", "2014 Fall" etc. ?

I was able to use

 gci | ? {$_.PSIsContainer} | select-string -pattern '\d+' 

to accomplish 1 and 2 but am stuck on using this to do part 3: actually rename by reversing the elements of the name. I tried putting the above within a variable and like so:

gci | ? {$_.PSIsContainer} | select-string -pattern '\d+' | %{$data = $_.line; Write-Output "$data"};

however, while the above outputs exactly the folders I want the array $data seems to only hold the last line of output. Such that:

gci | ? {$_.PSIsContainer} | select-string -pattern '\d+' | %{$data = $_.line; Write-Output "$data"};
$data 

will output:

test 123
test 321
test 321

I am unsure if this is even the a valid direction to begin with.

Any help would be greatly appreciated.


Solution

  • This should get the job done.

    $Path = "C:\Users\Test"
    $regex = "^(Spring|Summer|Fall|Winter)\s+\d{4}$"
    
    Get-ChildItem $Path | 
        Where-Object {$_.PSIsContainer -and $_.Name -match $regex} | 
        Rename-Item -NewName {$split = $_.Name -split "\s+"; "{0} {1}" -f $split[1],$split[0]}
    

    We use that regex to filter out the folder that fit your convention. Should be a little more targeted using specific season names. The year is a little more lacked by just looking for 4 numbers.

    Other ways to do it but for the rename I just split the name on the space and reversed the output using the -f format operator.