Home » PowerShell » PowerShell – Rename part of FileName

PowerShell – Rename part of FileName

Rename-Item cmdlet in PowerShell is used to rename part of the filename by passing the file path to be replaced with a new name.

The Rename-Item command doesn’t affect the content of the file. It only renames the item name.

Using the Rename-Item command in PowerShell, we can rename part of the file name in the specified folder path.

In this article, we will discuss how to rename part of the filename of multiple files in the specified directory using the Rename-Item cmdlet.

Rename Part of FileName in Directory

Use the Get-ChildItem cmdlet in PowerShell to get one or more file names from the directory and using the Rename-Item command, it will change the part of the file name with a new name.

 Get-ChildItem -Path D:\LogTest\FTP-02\ *.csv | Rename-Item -NewName {$_.Name -replace "Log_A","INCORP-A"} 

In the above PowerShell script, the Get-ChildItem command gets all the files in the specified directory that have the CSV file extension and then pipes them to the Rename-Item command.

The Rename-Item command uses the NewName parameter and uses the script block to replace the part of the filename with a new name using the -replace operator.

In the script block, the $_ automatic variable represents each file object and uses the -replace operator to replace the part of the file name which matches with the specified “Log_B” and to be replaced with “INCORP-B”

The output of the above PowerShell script to change part of the filename is:

PowerShell Rename part of the filename
PowerShell Rename part of the filename

In the above output windows, the Get-ChildItem command gets all the CSV files available in the specified directory path. The Rename-Item command changes the part of the file name “Log_B” with “INCORP-B”

Cool Tip: How to move files and rename with date in PowerShell!

Conclusion

I hope the above article on how to rename the part of the filename in PowerShell using the Rename-Item command is helpful to you.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.