File rename code assistance

Hi, I have a number of files that follow the same format I would like to bulk rename using PS.

The file format currently is:

YYYYMMDD - Title - Firstname Lastname.pdf

and I am hoping to bulk change them to the file naming convention my team is now using:

LASTNAME-FIRSTNAME-TITLE-YYYYMMDD.pdf

Note: The Title/TITLE part of the filename is generally a single acronym with no extra delimiters.

I am attempting to amend a code (full credit to a user from Reddit who helped me with that initial code) to use it for my application above.

After amending, the current code I have is:

dir | rename-item -newname { $date,$title,$name = $_.basename -split " - ",3; "$name-$title-$date.pdf".toupper() }

which returns:

FIRSTNAME LASTNAME-TITLE-YYYYMMDD.PDF

This is the first time I am trying to amend some code for renaming files that I for myself would consider “complex.”

Two points I cannot figure out how to do:

  • Convert in my result FIRSTNAME LASTNAME to LASTNAME-FIRSTNAME (My thoughts is this needs an extra “nested” -split with a space delimiter.
  • Leave the file extension, in this case .pdf, as lowercase.

Would anyone have any thoughts on how to amend the code to also achieve the above 2 points?

Hmmm … why don’t you ask follow up questions about your requirement on reddit? I’d expect them to help you further.

Please don’t use aliasses in scripts or here in the forum as it makes your code harder to read.

What have you tried? Use some test files and start trying … :man_shrugging:t3:

You already know how to split on a combination of characters. It’s not that hard to change that to a space, or is it? :man_shrugging:t3:

If you don’t want to change it. Don’t change it. :man_shrugging:t3: :wink:

Get-ChildItem | 
Rename-Item -newname { $Date, $Title, $Name = $_.BaseName -split " - ",3; $First, $Last = $Name -split ' ' ; "$Last-$First-$title-$Date".ToUpper() + $_.Extension }

It’s going to be a bit more code, but i’m a big fan of the “format operator.”

Get-ChildItem | Foreach-Object {
    $date,$title,$name = $_.basename -split " - ",3
    Rename-Item -NewName $('{0}-{1}-{2}.pdf' -f $name.ToUpper(),$title.ToUpper(),$date.ToUpper())
}

The Format Operator lets you define your string with positional placeholders for an array of input. It’s 0 indexed like all arrays in powershell. This could be reduced to less code, but I’m hoping this makes it easier to understand.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.