Batch File Search and Renaming with PowerShell

If it is necessary to rename a batch of files, where both the existing and new file names exist in an Excel spreadsheet, PowerShell can be used to automate the renaming process.

In the example below, a spreadsheet called “Documents to rename.xlsx” contains the file name information. Column ‘A’ contains the existing file name, without the file extension, column ‘B’ contains the new file name, if available, without the extension, and column ‘C’ is for notes to be added during the renaming process.

Existing File Name New File Name Notes
OldFileName1 NewFileName1
OldFileName2
OldFileName3 NewFileName3
OldFileName4 NewFileName4

First of all, the path to the above document, as well as to the files to be renamed, is set and a check is made to see if they exist. If they do exist, the document containing the file names is opened and the file name information on the first sheet is processed. The last row used is obtained and all the rows, from the second to the last are handled one by one. The current and new file names are extracted from columns ‘A’ and ‘B’, using their numerical references, 1 and 2. A check is made to see if the file exists with the current name and if it does the file gets renamed to the new name, providing there is one available. Feedback is added in column 3 as to whether the file was renamed or not, or, if it had already been renamed. Overall feedback is also given as to the total number of files renamed.

# Clear the console window.
Clear-Host

# Excel.
$excel = New-Object -ComObject Excel.Application

# File names workbook.
$pathNamesDoc = "C:\Demo\Rename\Documents to rename.xlsx"

# Path to documents to rename.
$pathDocsRename = "C:\Demo\"

# Check if the file and folder paths exist.
if ((Test-Path $pathNamesDoc) -and (Test-Path $pathDocsRename))
{

    try
    {

        # Open the file names workbook and assign to a variable.
        $xlNamesWorkbook = $excel.Workbooks.Open($pathNamesDoc)

    }
    catch
    {

        # Message stating that workbook can't be opened.
        Write-Host "Unable to open file names workbook."

        # Quit Excel and stop script execution.
        $excel.Quit()
        exit

    }

    # Select the first sheet.
    $xlNamesWorksheet = $xlNamesWorkbook.Sheets.Item(1)

    # Columns.
    $xlCurrentNameCol = 1
    $xlNewNameCol = 2
    $xlNotesCol = 3

    # Last row and file name variables.
    [long] $lastRow = 0
    [string] $currentFileName = $null
    [string] $newFileName = $null
    [string] $fileExtension = ".docx"

    # Renamed file count.
    [int] $filesRenamed = 0

    # Find the last row used.
    $lastRow = $xlNamesWorksheet.UsedRange.Rows.Count

    # Check if there are any files to rename.
    if ($lastRow -le 1)
    {

        # Message stating no files to rename.
        Write-Host "There are no files to rename."

    }
    else
    {

        # Message stating files are being processed.
        Write-Host "Processing files...`n"

        # Process the rows, from second row to the last used.
        for ($row = 2; $row -le $lastRow; $row++)
        {

            # Extract the current and new file name.
            $currentFileName = `
                $xlNamesWorksheet.Cells.Item($row, $xlCurrentNameCol).Value()
            $newFileName = `
                $xlNamesWorksheet.Cells.Item($row, $xlNewNameCol).Value()

            # Check if the file exists and a new name has been provided.
            if ((Test-Path ($pathDocsRename + $currentFileName + $fileExtension)) -and `
                (-not ([string]::IsNullOrEmpty($newFileName))))
            {

                # Add file extension to new file name.
                $newFileName = $newFileName + $fileExtension


                # Check if the new file name is valid.
                if ($newFileName.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) `
                    -eq -1)
                {

                    try
                    {

                        # Rename file.
                        Rename-Item -Path `
                            ($pathDocsRename + $currentFileName + $fileExtension) -NewName `
                            ($pathDocsRename + $newFileName)

                        # Add message in notes column stating file has been renamed.
                        $xlNamesWorksheet.Cells.Item($row, $xlNotesCol).Value() = ` 
                            "File has been renamed."

                        # Increment the files renamed count.
                        $filesRenamed += 1

                    }
                    catch
                    {

                        # Add message in notes column stating file can't be renamed.
                        $xlNamesWorksheet.Cells.Item($row, $xlNotesCol).Value() = ` 
                            "File could not be renamed."

                    }

                }
                else
                {

                    # Add message in notes column stating no new valid name provided.
                    $xlNamesWorksheet.Cells.Item($row, $xlNotesCol).Value() = ` 
                        "No new valid file name provided."

                }


            }
            else
            {

                # Check if new file name has been provided.
                if ([string]::IsNullOrEmpty($newFileName))
                {

                    # Add message in notes column stating no new file name provided.
                    $xlNamesWorksheet.Cells.Item($row, $xlNotesCol).Value() = ` 
                        "No new valid file name provided."

                }
                # Check if file has already been renamed.
                elseif (Test-Path ($pathDocsRename + $newFileName + $fileExtension))
                {

                    # Add message in notes column stating file already renamed.
                    $xlNamesWorksheet.Cells.Item($row, $xlNotesCol).Value() = `
                        "File has already been renamed."

                }
                else
                {

                    # Add message in notes column stating file does not exist.
                    $xlNamesWorksheet.Cells.Item($row, $xlNotesCol).Value() = `
                        "File does not exist."

                }

            }

        }

        try
        {

            # Save the file names workbook.
            $xlNamesWorkbook.Save()

        }
        catch
        {

            # Message stating file names workbook could not be saved.
            Write-Host "The file names workbook could not be saved."

        }

        # Feedback on renamed files.
        if ($filesRenamed -eq 0)
        {

            Write-Host "No files were renamed."

        }
        elseif ($filesRenamed -eq 1)
        {

            Write-Host "$filesRenamed file renamed successfully."

        }
        else
        {

            Write-Host "$filesRenamed files renamed successfully."

        }

    }

    # Close the file names workbook and quit Excel.
    $excel.Workbooks.Close()
    $excel.Quit()
    Stop-Process -name EXCEL

}
else
{

    # Check if it's the file or folder path that doesn't exist.
    if (-not (Test-Path $pathNamesDoc))
    {

        # Error message if file names workbook doesn't exist.
        Write-Host "The document containing the file names does not exist."

    }
    else
    {

        # Error if folder path for documents to be renamed doesn't exist.
        Write-Host "The location of the files to rename does not exist."

    }

}