We are continuing our series that answers common questions, or questions that have been asked about/of PowerShell. Today we Rename Files With PowerShell. What we intend to provide is one of the many, many ways you can accomplish these same tasks within PowerShell.
All of the solutions are ours and demonstrate the author’s skill and ability level at the time of writing. That is to say, we might not always write the best PowerShell code, however, if you know of a better way we welcome that input.
Let’s start. The question is:
How do you rename files with PowerShell?
The Answer:
The Rename-Item
cmdlet gives you the ability to change the name of an object while leaving the content inside it untouched and completely intact. It is not possible to move items with the Rename-Item command. If you are looking for that functionality, you should use the Move-Item
cmdlet as described in our other articles. Here is an example of renaming a text file
Rename-Item -Path "\\fileserver\SharedDirectory\SuperImportantFile.txt" -NewName "NotSoImportantFile.txt"
That worked too easy. Let’s do the same but add the date to the file. To do that we need to use Get-Date
and format for the string. Let me show you.
(get-date).ToString(`Mdy')
This command gets the current date and outputs MonthDayYear, as a string. Let’s put it together with the other command above.
$date = (get-date).ToString(`Mdy') Rename-Item -Path "\\fileserver\SharedDirectory\SuperImportantFile.txt" -NewName "NotSoImportantFile-$date.txt"
The above script not only renamed the file but it renamed the file and append the current date to the end of the file name.
What if we need to rename multiple files at once? We would need a loop. The easiest way I can think of to do a loop for this would be a foreach
loop. Foreach loops through a set of input objects and perform an operation {executes a block of statements} against each operation. What would that look like? Glad you asked:
$files = Get-ChildItem -Path \\fileserver\SharedDirectory\ foreach ($file in $files) { $newFileName=$file.Name.Replace("2020","2021") Rename-Item $file $newFileName }
The first line tells PowerShell that the variable $files
is going to host the list of files that we need to loop through. The next line begins to define the foreach
statement by saying for each $file
in $files
. The $file
variable is an automatic variable and can be called any name that is not already being used, or conflicts with PowerShell’s naming convention. The next line says find all files with 2020 and make them 2021. Lastly, the Rename-Item
renames the filename to the new file name we defined above.
If you liked this post checkout these below: