How to rename a file PowerShell
Every action in PowerShell is supported by a Cmdlet, Function or an Alias. Here, we are targeting to rename a file. The Rename-Item Cmdlet of PowerShell allows you to rename files from PowerShell. The Rename-Item cmdlet functions on the syntax provided below:
The syntax written below is practiced by renaming a file that is available at your current working directory.
However, you can also rename a file that is placed at some other location on your machine. For this, you have to provide the path of that file by using the Path parameter as described in the syntax below:
We have provided various examples that rename in both contexts.
Example 1: Rename a file in the current directory
We are currently logged into the F: drive and executed the ls command to get the files/directories inside F: drive:
We will rename the file named demo.txt to linuxhint.txt. To do so, the command written below is executed:
Example 2: Rename a file that is present in another location(s)
If the files that you want to rename reside other than the current working directory location, then you have to give the path of that file by using the -Path parameter. For instance, the command provided below will rename a file that resides at “D:\” and the complete path to that file is “D:\conference.docx“. It is observed that the command changes the name and the extension of the file as well.
Example 3: Using the Confirm parameter
The confirm parameter will confirm before executing the command. For instance, the command written below makes use of the “Confirm” parameter of the “Rename-Item” cmdlet to change the name of file “E:\locate.txt” to “conference.txt”. As the command is executed,
Example 4: Using the Passthru parameter
The Passthru parameter of PowerShell prints the output of the Rename-Item cmdlet. The default execution of Rename-Item does not show any results on the console. To get the output on the PowerShell screen as well, you must use the Passthru parameter. We have used the Rename-Item to rename file “E:\conference.txt” to “locate.txt” using the Passthru parameter:
Conclusion
PowerShell cmdlets provide extended functionality to perform some basic as well as advanced level operations. The Rename-Item cmdlet of PowerShell enables you to rename files in PowerShell. This article explains the method to rename a file in PowerShell. A file can be renamed easily using the Rename-Item cmdlet of PowerShell. If the file resides in your current working directory, then only the filename is sufficient. However, if a file resides at some other location, then you have to provide the complete path of the file.