What is the Rename-Item cmdlet in PowerShell?
Overview
The Rename-Item cmdlet is used to rename a file with a new name.
Syntax
Rename-Item -Path "path of the old file" -NewName "new name of the file"
Parameters
Path: This is the path to the old file.NewName: This is the new name to rename the file.
Return value
It doesn't return anything.
Example
In the following example, we rename the file abc.txt to def.txt using the cmdlet Rename-Item. We validate it by looking at filenames before and after the rename.
example.ps1
abc.txt
#!/usr/bin/pwsh -CommandWrite-Host "------------List of files before renamig the file------------"Get-ChildItem -Name#rename the fileRename-Item -Path "abc.txt" -NewName "def.txt"Write-Host "------------List of files after renamig the file------------"Get-ChildItem -Name
Explanation
- Line 4: We display the files in the current directory using the cmdlet
Get-ChildItem. Here, we can see that the file has the nameabc.txt. - Line 7: We rename the file
abc.txttodef.txtusing the cmdletRename-itemand pass the path asabc.txtandNewNameasdef.txt. - Line 10: We display the files in the current directory using the cmdlet
Get-ChildItem.Here, we can see that the file name has been changed todef.txt.