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.

1 Answer 1

0

Instead of Select-String, use object's properties:

# Path to folder
$Path =  '.\'

# Regex to match 'SEASON YEAR' and extract capture groups
$Regex = '^(\w+)\s(\d+)'

# Get all objects in path
Get-ChildItem -Path $Path |
    # Select only objects that are directory and name matches regex
    Where-Object {$_.PSIsContainer -and $_.Name -match $Regex} |
        # For each such object
        ForEach-Object {
            # Generate new name
            $NewName = $_.Name -replace ($Regex, '$2 $1')

            # Rename object
            Rename-Item -Path $_.FullName -NewName $NewName
        }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .