1

I have an old server archived and would like to rename all the files by adding the last modified date to the file name. There are many layers of folders in the directory structure.

I have tried a few different versions of scripts and the first level works fine, then it errors on the sub folders.

Error:

Rename-Item : Cannot rename because item at 'Stand.doc' does not exist.
At line:1 char:42
+ ... ch-Object { Rename-Item $_ -NewName ("{0}-{1}{2}" -f $_.BaseName,$_.L ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand*

Stand.doc is a file from a sub directory.

Semi-Working script:

Get-ChildItem -recurse |Foreach-Object { Rename-Item $_ -NewName ("{0}-{1}{2}" -f $_.BaseName,$_.LastWriteTime.ToString('"Last_Mod_Date_"mmddyyyy'),$_.Extension)  }

Thank you

codewario
  • 19,553
  • 20
  • 90
  • 159
  • 1
    Since you only want to rename files you should add the switch parameter `-File` for `Get-ChildItem`. ;-) – Olaf May 06 '22 at 14:44
  • If you already read my answer, I've updated it. I originally tried this in PS Core but I can reproduce the problem in PowerShell 5.1 (the version baked into Windows). I don't have a solution for 5.1 yet, but I will try to revisit this later. – codewario May 06 '22 at 15:00

1 Answers1

1

I've been able to reproduce this with Windows PowerShell (5.1) after all but I cannot reproduce it in PowerShell Core 7.2.3. I'm not quite sure what the issue here is but this answer should only be considered relevant for PowerShell Core. I will try to revisit this later to see if I can't figure out what's going on with PowerShell 5.1.

You will want to use the -File parameter with Get-ChildItem. The following should work for you to only return nested files so you don't accidentally try renaming directories:

Get-ChildItem -Recurse -File | Foreach-Object {
  Rename-Item -WhatIf $_ -NewName ( "{0}-{1}{2}" -f $_.BaseName, $_.LastWriteTime.ToString('"Last_Mod_Date_"mmddyyyy'), $_.Extension )
}

I've added a -WhatIf parameter to Rename-Item, once you confirm the correct file list will be renamed, you can remove this to actually have the rename operation work.

codewario
  • 19,553
  • 20
  • 90
  • 159
  • Yea, I had different iterations of this and I did accidentally leave out "-File" in the post, Sorry. It sees the files in the file tree, just errors on the -Newname. – John Rothenberger May 09 '22 at 18:51