Rename a file or a folder by appending the current date and time to the existing file or folder name:
#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"
Example
Assuming stampme.ps1 is saved in the current directory:
PS C:\>./stampme.ps1 "F:\work\some file.txt" > F:\work\some file-2009-11-30@09-30-00.txt
“Two roads diverged in a wood, and I, I took the one less traveled by, And that has made all the difference” ~ Robert Frost (The Road Not Taken)
Related:
Rename-Item - Change the name of an existing item
Touch - Change the date/time of a file/folder
Standard date and time notation - YYYY-MM-DD
StampMe.cmd - Rename a file (CMD script)
© Copyright SS64.com 1999-2013
Some rights reserved