renaming files

Welcome Forums General PowerShell Q&A renaming files

Viewing 2 reply threads
  • Author
    Posts
    • #212742
      Participant
      Topics: 12
      Replies: 11
      Points: 156
      Rank: Participant

      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.

       

      Many thanks

       

    • #212766
      Participant
      Topics: 4
      Replies: 2249
      Points: 5,494
      Helping Hand
      Rank: Community MVP

      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 |
          ForEach-Object {
              $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. 😉

    • #212781
      Participant
      Topics: 6
      Replies: 667
      Points: 97
      Helping Hand
      Rank: Member

      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.

      • This reply was modified 2 months, 1 week ago by Curtis Smith.
Viewing 2 reply threads
  • You must be logged in to reply to this topic.