Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rename files using Powershell must include GetDate & Increment numbers

I am struggling to get this Powershell code to work below. I would like to rename files as per below.

06.09.2022_15.05. MYUSER 1

If there is multiple files in the folder then be able to increment
06.09.2022_15.05. MYUSER 1
06.09.2022_15.05. MYUSER 2
06.09.2022_15.05. MYUSER 3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

below is the code i am using but it is not working (obviously)

 $GetUser = [Environment]::UserName
 $i = 1
 Get-ChildItem *.pdf | 
 rename-item -NewName {((get-date).ToString("dd.MM.yyyy_HH.mm.")+" "+," "+ $GetUser +,$_.Extension -f $i++ )}

This returns

06.09.2022.15.05. MYUSER

As you can see it doesn’t have the incremented number at the end

>Solution :

There are two problems with your current script: you’re not providing an appropriate template string for the -f operator, and that the Rename-Item -NewName block will execute in its own local scope, meaning the original value of $i is never modified when you do $i++ inside the -NewName scriptblock.

Use ForEach-Object to construct the new name ahead of time, then pass it to Rename-Item:

$username = [Environment]::UserName
$counter = 1
$timestamp = Get-Date -Format 'dd.MM.yyyy_HH.mm.'

Get-ChildItem *.pdf |ForEach-Object {
  $newName = "{0} {1} {2}{3}" -f $timestamp,$username,$counter++,$_.Extension

  $_ |Rename-Item -NewName $newName
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading