Problem
You want to rename a file or directory.
Solution
To rename an item in a provider, use the RenameItem cmdlet: PS > RenameItem example.txt example2.txt
Discussion
The RenameItem cmdlet changes the name of an item. While that may seem like pointing out the obvious, a common mistake is:
PS >RenameItem c:\temp\example.txt c:\temp\example2.txt RenameItem : Cannot rename because the target specified is not a path. At line:1 char:12
+ RenameItem <<<< c:\temp\example.txt c:\temp\example2.txt
In this situation, PowerShell provides a (not very helpful) error message because we specified a path for the new item, rather than just its name.
One thing that some shells allow you to do is rename multiple files at the same time. In those shells, the command looks like this:
ren *.gif *.jpg
PowerShell does not support this syntax, but provides even more power through its –replace operator. As a simple example, we can emulate the preceding command: GetChildItem *.gif | RenameItem NewName { $_.Name replace '.gif$','.jpg' }
This syntax provides an immense amount of power. Consider removing underscores from filenames and replacing them with spaces:
GetChildItem *_* | RenameItem NewName { $_.Name replace '_',' ' } or restructuring files in a directory with the naming convention of Report_Project_ Quarter.txt:
PS >GetChildItem | 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 >GetChildItem | >> RenameItem NewName { $_.Name replace '.*_(.*)_(.*)\.txt','$2_$1.txt' } >> PS >GetChildItem | Select Name
Name
Q1_Project2.txt Q3_Project1.txt Q4_Project1.txt
Like the other *Item cmdlets, the RenameItem doesn’t work only against the filesystem. Any providers that support the concept of items automatically support this cmdlet as well. For more information about the RenameItem cmdlet, type GetHelp RenameItem.