How to Rename a File in PowerShell?

Requirement: Rename a file using PowerShell.

PowerShell to Rename a File

Renaming files is one of the common tasks that system administrators and developers perform. PowerShell provides a set of cmdlets for managing files, including renaming them. The Rename-Item cmdlet is used to rename files and folders in PowerShell. Renaming files can be a time-consuming process, especially when you have to alter many files at once. Thankfully, PowerShell allows you to rename multiple files quickly. In this article, we will show you how to rename a file using PowerShell.

Renaming a single file using PowerShell

To rename a file using PowerShell, you can use the Rename-Item cmdlet, you need to specify the path to the file and the new name of a specified item you want to give it. For example, to rename a file called oldname.txt to newname.txt, you can use the following command:

Rename-Item -Path C:\Example\oldname.txt -NewName C:\Example\newname.txt

This will rename the file from oldname.txt to newname.txt in the C:\Example directory.

PowerShell to rename a file – Overwrite existing

The Rename-Item cmdlet cannot overwrite existing files (However, You can test if the target file exists and then delete it!). Use the Move-Item cmdlet instead to rename a file with the “Force” switch. This cmdlet allows you to specify both the source path of the item and the destination path, which can include a new file name. Here’s an example of how you can use the Move-Item cmdlet to move and rename a file:

Move-Item -Path C:\Temp\Oldname.txt -Destination C:\Temp\newname.txt -Force

Note that you will need to have the appropriate permissions to rename a file in the specified location. It has a -Force parameter that can be used to override any errors that might occur during the move operation, such as overwriting any existing files.

PowerShell to Rename multiple files

You may have experienced the need to rename multiple files at once. To rename multiple files in PowerShell, you can use the Get-ChildItem cmdlet to get a list of the files you want to rename, and then pipe the list to the Rename-Item cmdlet. You can use wildcards to specify the files you want to rename, and you can use the -NewName parameter of the Rename-Item cmdlet to specify the new names for the files.

Let’s recursively replace the “Space” character with “-” in all selected files from a Folder and its sub-folders.

Get-ChildItem -Path "C:\Temp" -Recurse -Include "*.txt" | Rename-Item -NewName { $_.Name -replace " ","-" }

Rename all files in a Folder with an increasing number:

Get-ChildItem -Path "C:\Temp" -Recurse -Include "*.txt" | ForEach-Object -Begin { $Counter = 1 } -Process { Rename-Item $_ -NewName "Log_$Counter.log" ; $Counter++ }

Instead of using the -include and -exclude parameters, you can send the results down the pipeline and pipe them to the Where-object cmdlet.

Rename all files by adding the time stamp in file names:

#Get the Timestamp
$TimeStamp = Get-Date -F yyyy-MM-dd_HH-mm

#Get all text files from a Folder and rename them by appending Timestamp
Get-ChildItem -Path "C:\Temp" -Recurse -Include "*.txt" | ForEach-Object { 
    Rename-Item -Path $_.FullName -NewName "$($_.DirectoryName)\$($_.BaseName)_$TimeStamp$($_.Extension)"
}

Rename all the files in the current directory, prefixing each with “AppLog – “:

#Get all text files from a Folder and rename them by appending Timestamp
Get-ChildItem -Path "C:\Temp" -Recurse -Include "*.txt" | ForEach-Object {
    Rename-Item $_.FullName -NewName "$($_.DirectoryName)\AppLog - $($_.BaseName)$($_.Extension)"
}

Bulk Rename All Files in a Directory

We need to use a loop to iterate over the files in the folder and rename them one by one. Here is an example of how to filter and rename a series of files named “abc.txt”, “def.txt”, “xyz.txt”, etc. to “file1.csv”, “file2.csv”, “file3.csv”, etc. You can use the following script. This will rename the files in a sequential manner, incrementing the number at the end of the filename for each file.

$i = 1
Get-ChildItem -Path C:\Temp\*.txt | ForEach-Object {
   Rename-Item $_ -NewName "File$i.csv"
   $i++
}

This command uses the Get-ChildItem cmdlet to get all files with the .txt extension in the Temp folder. It then uses the ForEach-Object cmdlet to iterate over each file and replace the .txt extension with the .csv extension.

Batch renaming files with PowerShell scripts

Renaming multiple files in a folder can be a tedious and error-prone task, especially if you have a large number of files to rename. PowerShell scripts can help automate this task and save you time and effort. Here’s an example of a PowerShell script that renames all files in a folder to have a prefix and a suffix:

#Parameters
$Folder = "C:\Reports"
$Prefix = "MyPrefix_"
$Suffix = "_MySuffix"

#Add Prefix and Suffix to All Files in the Folder
Get-ChildItem -Path $Folder | ForEach-Object {
    $NewName = '{0}{1}{2}{3}' -f $Prefix,$_.BaseName,$Suffix,$_.Extension
    Rename-Item -Path $_.FullName -NewName $NewName
}

This script uses the Get-ChildItem cmdlet to get all files in the specified folder. It then uses the ForEach-Object cmdlet to iterate over each file and rename it using the prefix and suffix specified in the variables.

Renaming file extensions with PowerShell

PowerShell provides a simple way to rename file extensions using the -replace operator. Here’s how to rename all files with the .txt extension to have the .log extension:

#Get All Txt Files from C:\Logs Folder
$Files = Get-ChildItem C:\Logs\*.txt

#Change File extention from .txt to .log
ForEach ($File in $Files) {
    Rename-Item -Path $File.FullName -NewName ($File.Name -replace ".txt", ".log")
    Write-host "Renamed File:"$File.FullName
}

This will rename all of the .txt files in the C:\Logs directory to have an .txt extension. It uses the -replace operator to replace the .txt extension with .log while keeping the rest of the filenames the same.

PowerShell to rename if File exists

When renaming files in PowerShell, you may encounter situations where the new file name you want to use already exists. To avoid overwriting existing files, you can check if a file exists before renaming it. To rename a file in PowerShell if it exists, you can use the Test-Path cmdlet to check if the file exists, and then use the Rename-Item cmdlet to rename the file. Here’s an example of how you can do this:

#Parameter
$OldFile = "C:\Logs\OldFile.txt"
$NewFile = "C:\Logs\NewFile.log"

#PowerShell to rename file if exists
If (Test-Path $OldFile) {
    Rename-Item -Path $OldFile -NewName $NewFile
    Write-host "'$OldFile' has been renamed to '$NewFile'" -f Green
}
Else{
    Write-host "'$OldFile' does not exists!" -f Yellow
}

This will check if oldFile.txt exists in the specified path. If it does, it will be renamed to newFile.log. If the file doesn’t exist, the Rename-Item cmdlet will not be executed, and the script will continue running. How about checking if the target file exists and deleting it, before renaming the old file?

#Parameter
$OldFile = "C:\Logs\OldFile.txt"
$NewFile = "C:\Logs\NewFile.log"

#PowerShell to rename file if exists
If (Test-Path $OldFile) {
    #Check if the Target File Exists
    If (Test-Path $NewFile) {
        #Delete the target file
        Remove-Item $NewFile
    }
    Rename-Item -Path $OldFile -NewName $NewFile
    Write-host "'$OldFile' has been renamed to '$NewFile'" -f Green
}
Else{
    Write-host "'$OldFile' does not exists!" -f Yellow
}

Conclusion

In conclusion, PowerShell can make time-consuming tasks like renaming your large batch of files much simpler and faster. It allows you to use wildcard characters, and other advanced features to rename multiple files at once. It also allows you to preview the changes before committing them using “-WhatIf” switch, which can be helpful in avoiding mistakes. Similarly, the -confirm Prompt for confirmation before executing the command. In this guide, we explored the different ways to rename files using PowerShell, including renaming a single file, renaming multiple files in a folder, batch renaming files with PowerShell scripts, and renaming file extensions. Overall, PowerShell makes it easy to rename files quickly and efficiently, making it a valuable tool for anyone working with large numbers of files.

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

Leave a Reply

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