Home > Software design >  using PowerShell to rename all files in a folder to each files last write time
using PowerShell to rename all files in a folder to each files last write time

Time:06-08

$getdate = Get-Date -Format "yyyymmddHHmmss"
Get-ChildItem -Path C:\blah\*.tiff | foreach { rename-item -Path $_.FullName -NewName "($getdate).tif" }

This just tells me that the file already exists as if its trying to change them all to the same date and time.

This is what each file should be renamed as though but ending in .tif and not .tiff.

Get-ChildItem -Path C:\blah\*  | Get-Date -Format "yyyymmddHHmmss"

20221413111408
20222013112039
20225413115422
20221816071813

How do I get this to work so that each file that comes into his folder is renamed when I run this.

I have also tried this:

Get-ChildItem -Path C:\Blah\*.tiff | foreach { rename-item -Path $_.FullName -NewName "Get-Date -Format ("yyyymmddHHmmss").tif" }

Which gives me this error:

Rename-Item : A positional parameter cannot be found that accepts argument 'yyyymmddHHmmss).tif'.
At line:1 char:52
  ... | foreach { rename-item -Path $_.FullName -NewName "Get-Date -Format  ...
                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : InvalidArgument: (:) [Rename-Item], ParameterBindingException
      FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.RenameItemCommand

CodePudding user response:

It's currently trying to rename all files to the same date timestamp because you're asking it to - the value stored in $getdate is not going to automatically update itself :)

Instead, you'll want to call Get-Date every time you rename an individual file by passing a scriptblock to the -NewName parameter - PowerShell will then re-evaluate the scriptblock for every file it's renaming:

Get-ChildItem -Path C:\blah*.tiff |Rename-Item -NewName { "$($_ |Get-Date -Format 'yyyymmddHHmmss').tif" }

As Santiago points out, this will still fail with a naming collision if you have multiple image files that were last written/modified within the same wallclock second.

  • Related