Home > Software engineering >  Rename files using Powershell must include GetDate & Increment numbers
Rename files using Powershell must include GetDate & Increment numbers

Time:09-07

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

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

CodePudding user response:

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
}

CodePudding user response:

Not to take away from Mathias' helpful solution, but to offer an alternative using a reference variable type:

 [ref]$i = 1
 $date = (Get-Date).ToString("dd.MM.yyyy_HH.mm.")
 Get-ChildItem -Filter '*.pdf' | 
    Rename-Item -NewName { "{0} {1} {2}{3}" -f $date, $env:USERNAME, $i.Value  , $_.Extension } -WhatIf

Same results, just using [ref] type to access the counter variable ($i) we're looking to increment; same difference.

  • Related