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"
For instructions of how to download and run this script see: Run a PowerShell script.
For a one line version of this see the Rename-Item page.
Examples
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
Rename a collection of .txt files:
foreach ($file in get-ChildItem *.txt) { ./stampme.ps1 $file.name }
“Two roads diverged in a wood, and I, I took the one less traveled by, And that has made all the difference” ~ Robert Frost
Related PowerShell Cmdlets:
Rename-Item - Change the name of an existing item.
Touch - Change the date/time of a file/folder.
Set-LastWrite - Reset Folder 'Last Modified' to the most recent file in the folder (PowerShell function).
set-eol - Change the line endings of a text file.
Standard date and time notation - YYYY-MM-DD
StampMe.cmd - Rename a file (CMD script).