Recently, I was working on a project for a client in New York where I needed to automate the process of checking for the existence of specific files and renaming them according to a predefined naming convention. You can do this easily with PowerShell scripts. In this tutorial, I will explain how to use PowerShell to check if a file exists and rename it with examples.
Now, let me show you how to check if a file exists and rename it using PowerShell with some real examples.
Check if a File Exists in PowerShell
PowerShell provides several methods to check if a file exists. I will show you two useful methods with examples.
1. Using Test-Path Cmdlet
The Test-Path
cmdlet is the best way to check if a file exists in PowerShell. It returns $true
if the file exists and $false
if it doesn’t. Here’s an example:
$filePath = "C:\MyFolder\report.txt"
if (Test-Path $filePath) {
Write-Host "The file exists."
} else {
Write-Host "The file does not exist."
}
I executed the above PowerShell script using VS code, and you can see the exact output in the screenshot below:
Check out Download a File from URL Using PowerShell
2. Using Get-Item Cmdlet
Another way to check if a file exists is by using the Get-Item
cmdlet. If the file exists, it will return a FileInfo
object; otherwise, it will throw an error. Here’s an example:
$filePath = "C:\MyFolder\MyPDFFile.pdf"
try {
$file = Get-Item $filePath
Write-Host "The file exists."
} catch {
Write-Host "The file does not exist."
}
Get-Item is useful when retrieving additional information about the file, such as its size, creation time, or attributes.
Here is the exact output in the screenshot below:
Read How To Check If File Modified In Last 24 Hours Using PowerShell?
Rename a File in PowerShell
Once you have checked that a file exists, you might want to rename it. PowerShell provides the Rename-Item
cmdlet for this purpose. Here’s an example:
$oldFilePath = "C:\MyFolder\sales_report.csv"
$newFilePath = "C:\MyFolder\sales_report_2024.csv"
if (Test-Path $oldFilePath) {
Rename-Item $oldFilePath $newFilePath
Write-Host "File renamed successfully."
} else {
Write-Host "The file does not exist."
}
In this example, we first check if the file exists using Test-Path
. If it does, we use the Rename-Item cmdlet to rename it from sales_report.
csv to sales_report_2023.csv
.
Here is the exact output in the screenshot below:
Read How to Create a Folder If Not Exists in PowerShell?
Handle File Name Collisions
When renaming files, you may encounter a situation where a file with the new name already exists. By default, Rename-Item
will throw an error in such cases. However, you can use the -Force
parameter to overwrite the existing file. Here’s an example:
$oldFilePath = "C:\MyFolder\budget.csv"
$newFilePath = "C:\MyFolder\budget_2024.csv"
if (Test-Path $oldFilePath) {
Rename-Item $oldFilePath $newFilePath -Force
Write-Host "File renamed successfully. Existing file overwritten."
} else {
Write-Host "The file does not exist."
}
In this case, if a file named budget_2024.csv
already exists, it will be overwritten by the renamed file.
Check out How to Create a File in PowerShell if it Doesn’t Exist?
PowerShell Check if a File Exists and Rename it with Today’s Date
In this example, I will show you how to check if a file exists and rename the file by appending today’s date to the existing file name using PowerShell.
Here is the complete PowerShell script.
$filePath = "C:\MyFolder\report.txt"
if (Test-Path $filePath) {
$currentDate = Get-Date -Format "yyyyMMdd"
$fileExtension = [System.IO.Path]::GetExtension($filePath)
$newFileName = "{0}_{1}{2}" -f [System.IO.Path]::GetFileNameWithoutExtension($filePath), $currentDate, $fileExtension
$newFilePath = Join-Path -Path (Split-Path $filePath -Parent) -ChildPath $newFileName
Rename-Item $filePath $newFilePath
Write-Host "File renamed successfully to $newFileName"
} else {
Write-Host "The file does not exist."
}
Let me explain this PowerShell script:
- We define the
$filePath
variable with the path to the existing file we want to check and rename. - We use the
Test-Path
cmdlet to check if the file specified by$filePath
exists.- If the file exists, the script enters the
if
block.- Inside the
if
block, we useGet-Date
with the-Format
parameter to get today’s date in the format “yyyyMMdd” and store it in the$currentDate
variable. - We use
[System.IO.Path]::GetExtension()
to extract the file extension from the original file path and store it in the$fileExtension
variable. - We then construct the new file name by combining the original file name (without extension), today’s date, and the file extension using the
"{0}_{1}{2}"
format string. The result is stored in the$newFileName
variable. - We use
Join-Path
to combine the parent directory of the original file path (obtained usingSplit-Path
) with the new file name to create the complete new file path. The result is stored in the$newFilePath
variable. - We use the
Rename-Item
cmdlet to rename the file from$filePath
to$newFilePath
. - Finally, we use
Write-Host
to display a success message indicating that the file was renamed, including the new file name.
- Inside the
- If the file does not exist, the script enters the
else
block.- Inside the
else
block, we useWrite-Host
to display a message indicating that the file does not exist.
- Inside the
- If the file exists, the script enters the
This script dynamically renames the existing file by appending today’s date to the original file name. For example, if the original file name is “report.txt” and today’s date is June 12, 2024, the renamed file will be “report_20240612.txt”.
Here is the exact output in the screenshot below:
Read How to Create a Log File using PowerShell?
Example
Let me share a real-world example from my experience. I was working on a project for a client in Chicago where I needed to process a large number of CSV files daily. The files followed a specific naming convention, such as sales_data_YYYYMMDD.csv
. My task was to check if the files existed and rename them to include the store location, like sales_data_YYYYMMDD_chicago.csv
.
Here’s the PowerShell script I used to accomplish this:
$sourceFolder = "C:\Data\SalesReports"
$destinationFolder = "C:\Data\ProcessedReports"
$storeLocation = "chicago"
$files = Get-ChildItem $sourceFolder -Filter "sales_data_*.csv"
foreach ($file in $files) {
$oldFilePath = Join-Path $sourceFolder $file.Name
$newFileName = $file.BaseName + "_" + $storeLocation + $file.Extension
$newFilePath = Join-Path $destinationFolder $newFileName
if (Test-Path $oldFilePath) {
Rename-Item $oldFilePath $newFilePath
Write-Host "File $($file.Name) renamed to $newFileName"
} else {
Write-Host "File $($file.Name) does not exist."
}
}
In this script, we:
- Define the source and destination folders and the store location.
- Use
Get-ChildItem
to retrieve all CSV files matching the patternsales_data_*.csv
in the source folder. - Loop through each file and construct the old and new file paths.
- Check if the file exists using
Test-Path
. - If the file exists, rename it using
Rename-Item
and move it to the destination folder.
Conclusion
In this tutorial, I explained various methods to check if a file exists using PowerShell, such as Test-Path
and Get-Item
. We also learned how to rename files using the Rename-Item
cmdlet and handle file name collisions with the -Force
parameter. Here, I explained how to check if a file exists and rename it using PowerShell.
You may also like:
- PowerShell Copy-Item with Folder Structure
- Get-ChildItem Sort By Date in PowerShell
- How to Get File Size Using PowerShell?
- How to Get the Last Modified Date of a File in PowerShell?
- How to Rename Multiple Files Using PowerShell?
I am Bijay a Microsoft MVP (10 times – My MVP Profile) in SharePoint and have more than 17 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com