I am trying to put together a Powershell script that will:
-Search recursively from a root directory
-Exclude files with existing "yyyyMMdd " file name prefix
-Rename the files not excluded above with ""yyyyMMdd " file name prefix based on their specific LastWriteTime
Note: ideally, this script should include all file type extensions
I have tried myself, but it would seem to be above my head, as my attempts are not going well.
Thanks, in advance.
http://ss64.com/ps/syntax-stampme.html
#StampMe.ps1
param( [string] $fileName)
# Check the file exists
if (-not(Test-Path $fileName)) {break}
# Display the original name
"Original filename: $fileName"
$fileObj = get-item $fileName
# Get the date
$DateStamp = get-date -uformat "%Y-%m-%d@%H-%M-%S"
$extOnly = $fileObj.extension
if ($extOnly.length -eq 0) {
$nameOnly = $fileObj.Name
rename-item "$fileObj" "$nameOnly-$DateStamp"
}
else {
$nameOnly = $fileObj.Name.Replace( $fileObj.Extension,'')
rename-item "$fileName" "$nameOnly-$DateStamp$extOnly"
}
# Display the new name
"New filename: $nameOnly-$DateStamp$extOnly"
I am hoping to change the line:
$DateStamp = get-date -uformat "%Y-%m-%d@%H-%M-%S"
To be LastWriteTime instead of get-date, but I have no idea how to make this happen.
This code (from another Super User question):
Get-ChildItem "Test.pdf" | Rename-Item -newname {$_.LastWriteTime.toString("yyyyMMdd") + " Test.pdf"}
…successfully renames a single file, but I can't seem to integrate this into the larger script.
With regards to running the above recursively, I have tried this (also from http://ss64.com/ps/syntax-stampme.html):
foreach ($file in get-ChildItem *.* -recurse) { ./StampMe.ps1 $file.name }
Which succeeds to apply the PS script to files in the root directory, but fails to apply to any files in the sub-folder tree that propagates from the root directory.
Best Answer
This script should do exactly what you want
Warning: You should test this script first because renaming could be dangerous. Remove the
#
in front ofRename-Item
after you have verified that only intentional files will be renamed.Long version
Short version
Used stackoverflow answers
[DateTime]::TryParseExact
to test if the first 8 characters can be a valid date$_.lastwritetime.tostring("yyyyMMdd ")
to format the lastwrite stamp