Using Powershell to Rename Files in Bulk

Shane 1 Reputation point
2021-07-02T12:45:04.987+00:00

I have hundreds of files that I'm wanting to rename using a Powershell script.

The files names are currently in this format: Data Extract Q2 AL.csv

I'm wanting to rename the files in the following format: 1234-AL-5-2Q21-Data.csv

All the quarters would all be in 2021 and the 5 just needs to be in the name of every file.

The 4 digit number is the issue that I'm having. Every state has a unique 4 digit number that matches the state that I need in the name of the file. I have an excel file that has the table with the states and their respective number, but I don't have the first clue of how to incorporate this into Powershell. Would this be more of a VBA problem?

Thank you

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2021-07-02T19:27:11.75+00:00

    The easiest way to do this (and probably the fastest) would be to construct a hash using the state abbreviation as the key and the state code as the value.

    Getting the data from an Excel file is easy if you install the ImportExcel module (available here: 7.1.0

    Here's an example:

    $h = @{}  
    $states = Import-Excel C:\junk\art.xlsx  
    # build a hash table  
    $states |  
        ForEach-Object{  
            $h[$_.State] = $_.Code  
        }  
    # get the file names  
    # .  
    # .  
    # .  
    # .  
    # assume that $StateName has been loaded with the name of a state  
    $StateName = "CO"  
    $StateCode = ""  
    if ($h.ContainsKey($StateName)){  
        $StateCode = $h.$StateName  
    }  
    else {  
        Write-Host "Oops! There's no state named $StateName in the spreadsheet!!!" -ForegroundColor Yellow  
    }  
    Write-Host "Code for state " $StateName " is " $StateCode  
    

    The spreadsheet in the example is just a simple one:
    111377-capture.jpg

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.