Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

20.13 Rename a File or Directory

Problem

You want to rename a file or directory.

Solution

To rename an item in a provider, use the Rename-Item cmdlet:

Rename-Item example.txt example2.txt

Discussion

The Rename-Item cmdlet changes the name of an item.

Some shells let you rename multiple files at the same time. In those shells, the command looks like this:

ren *.gif *.jpg

PowerShell doesn’t support this syntax, but provides even more power through its -replace operator. As a simple example, we can emulate the preceding command:

Get-ChildItem *.gif | Rename-Item -NewName { $_.Name -replace '.gif$','.jpg' }

This syntax provides an immense amount of power. Consider removing underscores from filenames and replacing them with spaces:

Get-ChildItem *_* | Rename-Item -NewName { $_.Name -replace '_',' ' }

or restructuring files in a directory with the naming convention of <Report_Project_ Quarter>.txt:

PS > Get-ChildItem | Select Name

Name
----
Report_Project1_Q3.txt
Report_Project1_Q4.txt
Report_Project2_Q1.txt

You might want to change that to <Quarter_Project>.txt with an advanced replacement pattern:

PS > Get-ChildItem |
    Rename-Item -NewName { $_.Name -replace '.*_(.*)_(.*)\.txt','$2_$1.txt' }

PS > Get-ChildItem | Select Name

Name
----
Q1_Project2.txt
Q3_Project1.txt
Q4_Project1.txt

For more information about the -replace operator, see Recipe 5.8.

Like the other *-Item cmdlets, the Rename-Item doesn’t work against only the filesystem. Any providers that support the concept of items automatically support this cmdlet as well. For more information about the Rename-Item cmdlet, type Get-Help Rename-Item.

See Also

Recipe 5.8, “Replace Text in a String”