Reputation: 11
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
Upvotes: 1
Views: 1044
Reputation: 21468
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.
Upvotes: 1