Rename Files with PowerShell

Rename Files with PowerShell

Rename Single File with PowerShell

Using Rename-Item with/without the -Path Parameter

Use the Rename-Item cmdlet to rename a file in PowerShell.

We used the Rename-Item cmdlet to rename the test.txt file to the newtest.txt file. Note that this command will look for the file in the current directory. If you want to search for a file from a different directory and rename it, then the following solution is for you.

Here, You must provide the file’s path using the -Path parameter. For instance, the command provided above will rename a file that resides at C:\ , don’t forget to add the file’s name in the path, for instance, C:\testnew.docx.

Note: The above command will also update the file’s extension from .docx to .txt.

Using Rename-Item with -Confirm Parameter

Use the Rename-Item cmdlet with the -Confirm parameter to prompt the user before renaming the file.

Here, we used the -Confirm parameter name to prompt the user whether s/he wants to rename the file. So, for example, the above command changes the name of the file "D:find.txt" to "testnew.txt" if and only if the user responds yes to the following prompt.

Using Rename-Item with -Passthru Parameter

Use the Rename-Item cmdlet with the -Passthru parameter to display data about the newly renamed file on the PowerShell console.

PowerShell returned the output to the console for the above command when we used the -Passthru parameter. It is most commonly used to ensure that the cmdlet does what we designed.

Rename multiple files in PowerShell

Use Rename-Item with Get-ChildItem cmdlet to rename multiple files.

Let’s say you want to change extension of all .txt files to .log files.

You can do it as following:

Get-ChildItem *.txt will retrieve all the txt files in the folder and pipe it to the Rename-Item cmdlet. Rename-Item cmdlet will change extension of each .txt file to .log.

Please note that we have used \ to escape . over here as -replace operator takes regex as input to search the String and . has special meaning in regex.

If you have extensions like .txt.txt by any chance, you can use following command.

-replace operator is used to replace String with new String.

Replace operator takes two arguments:

  • substring to find in given string : \.txt
  • replacement String for found String: .log.

In case you want to replace text, you can go through how to replace String in multiple files in PowerShell.

That’s all about how to rename files in PowerShell.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *