Friday, April 21, 2023

How to rename all files in a folder to the date and time of file Modified Date

 This is how you can rename all files inside a directory to the Modified date and time,



1. Open PowerShell

2. Inside PowerShell, navigate to that directory

3. Run the command in paragraph below:

 

Alternatively, you can do this:

1. Go to the folder that contains the files you want to rename.
2. Hold Shift key on your keyboard, and right click inside that folder

3. Select Open PowerShell Window here

 

4. Run the command below:

Get-ChildItem |Foreach-Object { Rename-Item $_ -NewName ("{0}{1}{2}" -f $_.LastWriteTime.ToString('yyyyMMddhhmmss'),$_.Extension)  }


If your original file is somefile.jpeg

The new name will become the modified date, for example: 20220214081125.jpeg

You can also add some text you want in front of the new file name using this command:

If I want to add the text: 'VID' in front of the file name I can use this command

Get-ChildItem |Foreach-Object { Rename-Item $_ -NewName ("{0}{1}{2}" -f 'VID',$_.LastWriteTime.ToString('yyyyMMddhhmmss'),$_.Extension)  }

Running the command I will give you the new file name VID20220214081125.jpeg

 

If you want to keep the original file name and add the modified date to the end of the file name you can use this command:


 Get-ChildItem |Foreach-Object { Rename-Item $_ -NewName ("{0}-{1}{2}" -f $_.BaseName,$_.LastWriteTime.ToString('yyyyMMddhhmmss'),$_.Extension)  }

Running the command I will give you the new file name somefile-20220214081125.jpeg

Explanation:

  • Get-ChildItem: Gets all items in the directory. You could add -Recurse to get files from sub directories too
  • Foreach-Object: Run the following code block with each file
  • $_: The current iterated file as an object
  • $_.BaseName: The filename without extension
  • $_.LastWriteTime: The last write time as a DateTime object
    The method .ToString() allows you to format as you need it
  • $_.Extension: The extension of the file