Rename a file by appending the current date and time to the existing filename:
param( [string] $fileName)
# Check the file exists
if (-not(Test-Path $fileName)) {break}
# Display the original name
"Original filename: $fileName"
$myfile = get-item $fileName
$extOnly = $myfile.extension
$nameOnly = $myfile.Name.Replace( $myfile.Extension,'')
# Get the date
$DateStamp = get-date -uformat "%Y-%m-%d@%H-%M-%S"
# Ensure its a file (not a folder) and rename
$fileName | Where {!$_.PSIsContainer} | rename-item -NewName "$nameOnly-$DateStamp$extOnly"
# Display the new name
"New filename: $nameOnly-$DateStamp$extOnly"
The key part of this script is the line $myfile = get-item $fileName this turns the string $filename into a powershell object we can easily manipulate.
Example
Assuming stamp.ps1 is saved in the current directory, run it passing the file to be renamed:
PS C:\>./stamp.ps1 "F:\some folder\somefile.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