fbpx Rename a File or Directory in PowerShell | Windows PowerShell, Windows Server | HostingUltraso.com
24/7/365 Support

Rename a File or Directory in PowerShell

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.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say