question

NativusN00b-9729 avatar image
0 Votes"
NativusN00b-9729 asked AndreasBaumgarten commented

How do I rename numbered files using powershell?

Hello,

I'd like to rename a batch of files with dates, written as follows:

text 2020-12
text 2020-11
text 2020-10
continuing to
text 2016-10

to

2020-12 - text
2020-11 - text

Thanks

windows-server-powershell
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @NativusN00b-9729 ,

Did the answer work for you? Are there any additional questions to this topic?

If you found the answer helpful, it would be great if you please mark it "Accept as answer". This will help others to find answers in Q&A

----------
Regards
Andreas Baumgarten

0 Votes 0 ·
AndreasBaumgarten avatar image
0 Votes"
AndreasBaumgarten answered AndreasBaumgarten edited

Hi @NativusN00b-9729 ,

maybe this is helpful to get started ( Use on your own risk!):

 ## Remove the -Whatif to execute the renaming ##
    
 # Rename one file - for instance for testing
 $file = "Junk/text 2020-12"
 $fileObj = Get-Item -Path $file
 $splitName = $fileObj.BaseName.Split(" ")
 $newName = $splitName[1] + " - " + $splitName[0] + ($fileObj.Extension)
 $fileObj | Rename-Item -NewName $newName -WhatIf
    
 # Rename files in folder
 $folder = "Junk/*"
 $files = Get-ChildItem -Path $folder -File -Include text*
 foreach ($obj in $files) {
     $fileObj = Get-Item -Path $obj
     $splitName = $fileObj.BaseName.Split(" ")
     $newName = $splitName[1] + " - " + $splitName[0] + ($fileobj.Extension)
     $fileObj | Rename-Item -NewName $newName -WhatIf
     }


(If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

Regards
Andreas Baumgarten




5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

IanXue-MSFT avatar image
0 Votes"
IanXue-MSFT answered IanXue-MSFT edited

Hi,

Please check to see if this works.

 $folder = 'C:\temp\'
 Get-ChildItem -Path $folder|ForEach-Object{
     $array = $_.BaseName -split ' '
     $newname = $array[-1] + ' - '+ ($array[0..($array.count-2)] -join ' ') + $_.Extension
     Rename-Item -Path $_.FullName -NewName $newname
 }

Best Regards,
Ian Xue
============================================
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.