Welcome › Forums › General PowerShell Q&A › renaming files
I am trying to turn a text file into a date name file for example when a log file or txt file is generated it automatically turns it into a mm-dd-yy name file.
I began building a prototype see below
Rename-Item “C:\temp\test.txt” -NewName (get-date -Format dd-mm-yy)
Now the above code works however i loose the .log or .txt file at the end. I attempted to append but it does not work. Does anyone have any idea how to retain the the file and keep the log or txt as the file extension.
You can use the parts of the orinignal name and extend it with a date …. like this:
Get-ChildItem -Path 'C:\temp' -Filter *.txt -File |
$newFileName = $_.BaseName + '_' + (Get-Date -Format 'yyyy-MM-dd') + $_.Extension
Rename-Item -Path $_.FullName -NewName $newFileName
BTW: If you’d tried to search for you’d have got thousand of examples like this in a matter of seconds. 😉
Could also just add the extension to the string
Rename-Item “C:\temp\test.txt” -NewName "$(get-date -Format dd-mm-yy).txt"
Olaf’s option is definitely better if you are dealing with multiple file extensions.