How to Rename a File in PowerShell?

Requirement: Rename a file using PowerShell.

PowerShell to Rename a File

Dealing with messy, disorganized filenames is a common headache for any computer user. You download files from the internet with random numbers or duplicate names. You have folders with images named DSC0001, DSC0002, and so on. Or you need to quickly rename batches of files for a project with a common prefix.

Renaming files is one of the common tasks you may need to perform, to organize the data and make it easier to find and access. Manually renaming files and folders one by one can take ages. This is where PowerShell comes to the rescue. With just a few PowerShell commands, you can rename multiple files based on search and replace, append timestamps, add numbering sequences, and much more.

In this beginner’s guide, we will explore the different options you have in PowerShell to rename files and folders in bulk. You will learn handy techniques like:

  • How to replace text in filenames using -replace
  • Adding prefixes/suffixes to multiple files
  • Removing or changing file extensions
  • Recursively renaming files in subfolders
  • Appending timestamps for versioning
  • Safely dealing with filename collisions

Whether you are a system admin managing servers or a regular PC user organizing folders, this tutorial will show you how to harness the power of PowerShell to eliminate filename chaos once and for all. Read on to learn how the Rename-Item cmdlet can help you rename files faster than you can manually!

Renaming a Single File using PowerShell

With PowerShell, you can easily modify file names, change file extensions, add prefixes or suffixes, and perform complex renaming operations with ease. The Rename-Item cmdlet in PowerShell allows you to rename items like files, folders, and registry keys. To rename a file using PowerShell, you can use the Rename-Item cmdlet. You need to specify the existing file path and the new name of a specified item you want to give it. Below is the basic syntax for the Rename-Item cmdlet.

Rename-Item [-Path] <String> [-NewName] <String> [-PassThru] [-Force] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>]

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. You can add PassThru parameter to the cmdlet to see the output in the Windows Powershell console.

powershell rename-item cmdlet

Overwrite an existing file in Rename

By default, The Rename-Item cmdlet can’t overwrite existing files. You’ll get an error message: “Rename-Item : Cannot create a file when that file already exists.” (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 requires you to specify both the source path of the file 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 and including hidden or read-only files.

PowerShell Rename-Item

Rename Multiple Files using PowerShell

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 to rename a file. 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 txt files from a Folder and its sub-folders.

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

Similarly, you can replace the old text with new text in file names using the following:

Get-ChildItem -Path "C:\Temp" | Rename-Item -NewName {$_.Name -replace "oldname", "newname"}

This command uses the Get-ChildItem cmdlet to retrieve all the files in the given directory (You can omit the path parameter to get all files in the current folder) and pass them to the Rename-Item cmdlet as pipeline input. The -replace operator replaces the specified string with the desired replacement.

Rename all files in a Folder with an increasing number:

Let’s suffix a sequence number to all log files in a directory:

Get-ChildItem -Path "C:\Temp\Logs" -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.

bulk rename powershell

Rename all files by adding the time stamp in file names

To add a timestamp suffix to all files in a folder, use:

#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)"
}

This gets the current date first and then appends it to the select file names.

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)"
}

Here, the $_ automatic variable represents each file object as it comes through the Get-ChildItem pipeline.

Bulk Rename All Files in a Directory

Batch renaming files in Windows File Explorer can be a time-consuming task, especially when dealing with a large number of files. Thankfully, there are efficient ways to automate this process using PowerShell.

We need to use a loop to iterate over the files in the folder and change the names of the files one by one in the script block. 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 on selected files.

Renaming Files with Sequential Numbers

You can use a loop and the format operator to add sequential numbers to the file names. This allows you to add a number to the end of each file name. Here’s an example:

$i = 1
Get-ChildItem -Path "C:\Docs" -File -Filter "*.zip" | ForEach-Object {
    $NewName = "File-{0:D3}{1}" -f $i, $_.Extension
    Rename-Item $_.FullName -NewName $NewName
    $i++
}

In this example, the loop iterates over each zip file, and the $i variable increments by 1. Here, the $_ represents the file object. The -f operator is used to format the new file name, where {0:D3} represents the sequential number with leading zeros and {1} represents the file extension.

Batch renaming files by Adding Prefixes or Suffixes 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.

Renaming Files with Regular Expressions (RegEx)

You can utilize regular expressions in PowerShell if you need to rename files using more complex patterns. Regular expressions allow you to match and replace specific patterns in the file names. Here’s an example:

Get-ChildItem -Path "C:\Docs" -File | Rename-Item -NewName {$_.Name -replace '(\d{4})-(\d{2})-(\d{2})', '$2-$3-$1'}

In this example, the regular expression pattern (\d{4})-(\d{2})-(\d{2}) matches dates in the format “YYYY-MM-DD” and swaps the position of the year and day, resulting in “MM-DD-YYYY” format. Here is another example of removing special characters from file names:

Get-ChildItem -Path "C:\Documents" -Filter "*.txt" | Rename-Item -NewName { $_.Name -replace "[^\w\s\.-]", "" }

In the above example, we are removing any special characters (excluding spaces and dashes) from the file names of all the files with the .txt extension in the C:\Documents directory. The regular expression pattern [^\w\s\.-] matches any character that is not a word character, a whitespace character, a dot, or a hyphen.

Rename Files to Sentence Case in PowerShell

If you want to rename files in a directory in sentence case (i.e., only the first letter of the filename is capitalized, and the rest are in lowercase) using PowerShell, you can do so with the following script:

# Directory path
$Directory = "C:\Temp\Logs"

#Get All Files from the Folder
Get-ChildItem -Path $Directory -File | ForEach-Object {
    #Frame the File name
    $NewName = ($_.BaseName.Substring(0,1).ToUpper() + $_.BaseName.Substring(1).ToLower()) + $_.Extension
    #powershell sentence case files
    Rename-Item -Path $_.FullName -NewName $NewName
}

How about changing file names to title case?

# Directory path
$Directory = "C:\Temp\Logs"

#Get the current system culture
$Culture = [System.Globalization.CultureInfo]::CurrentCulture
$TextInfo = $culture.TextInfo

# Get All Files from the Folder
Get-ChildItem -Path $Directory -File -Recurse | ForEach-Object {
    #Frame the File name
    $NewName = $textInfo.ToTitleCase($_.BaseName) + $_.Extension
    #Rename the File
    Rename-Item -Path $_.FullName -NewName $NewName
}

Rename if the File exists in PowerShell

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
}

You can also use unique prefixes/suffixes or timestamps to avoid collisions while generating new names in bulk rename operations.

PowerShell Move and Rename

We can also combine the Move-Item and Rename-Item cmdlets to move and rename a file in one step. For example, to move the file newreport.docx to the Archive folder and rename it:

# Rename and move an item
Move-Item -Path .\ApplicationLog.txt -Destination .\Archive\AppLog.txt

This moves and renames the file in one command. Make sure you have the target folder in place. Otherwise, you’ll face the “Move-Item : Could not find a part of the path.” error. More info on Move Files is here: How to Move a File in PowerShell?

PowerShell Rename Files – Use Cases:

Here are some common scenarios where you might want to rename files using PowerShell:

  • To clean up messy filenames or folder names with inconsistent naming conventions
  • To rename downloaded files by removing random digits appended to the filename – Batch rename files
  • To add or remove file extensions from multiple files at once
  • To append a timestamp or sequential numbering to filenames
  • To prepend client name or project name to batches of files
  • When migrating files from another system and the filenames need to be modified
  • For bulk post-processing of image, video or audio files

Renaming one or two files manually is easy. But for bulk renaming tasks, using PowerShell saves a lot of time and effort.

Conclusion

In conclusion, PowerShell can simplify and faster time-consuming tasks like renaming your large batch of files. 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 the “-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.

So next time you need to deal with a folder full of disorganized files, don’t waste time renaming them manually. Use PowerShell to rename files in bulk at lightning speed. The Rename-Item cmdlet and a few PowerShell tricks can save you hours of effort.

What is the command to rename a folder in PowerShell?

The command line tool to rename a folder in PowerShell is “Rename-Item”. E.g., Rename-Item -Path 'C:\old_folder' -NewName 'new_folder'
Here is the detailed post on How to Rename a Folder using PowerShell?

How do I rename all files in a folder and subfolders in PowerShell?

To rename all files in a folder and its subfolders using PowerShell, you can use the “Get-ChildItem” cmdlet to get all the files, and then use the “Rename-Item” cmdlet to rename them. Here is an example of the PowerShell script you can use to add prefixes to all files:
Get-ChildItem -Path "C:\Docs" -File -Recurse | ForEach-Object {
Rename-Item -Path $_.FullName -NewName ("new_" + $_.Name)
}

How to change the folder name from the command line?

To change the folder name using the command line, you can use the “ren” command followed by the current folder name and the new folder name. For example, if you want to change the folder name from “old_folder” to “new_folder”, you would type “ren old_folder new_folder” and press enter.

How do you move and rename a file in PowerShell?

To move and rename a file in PowerShell, you can use the Move-Item cmdlet. Here’s an example of how to do it:
Move-Item -Path "C:\Docs\Logs.zip" -Destination "C:\Docs\New-Logs.zip"

How do I Rename a key in the registry using PowerShell?

Apart from renaming files and Folders, the Rename-Item cmdlet can also used to rename registry keys and values. Here is an example:
Rename-Item -Path "HKCU:\Software\MyKey" -NewName "NewKey"
Set-ItemProperty -Path "HKLM:\Software\MyKey" -Name "OldValue" -Value "NewValue"

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

One thought on “How to Rename a File in PowerShell?

  • This is a great article. A little PS script can replace standalone programs for batch renaming.

    Reply

Leave a Reply

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