0

I am reading an CSV File in which, depending on the month, the column headers will have different names. They will always represent 3 months ago, 2 months ago, and 1 month ago, but will have column header names such as:

  • Actuals(-3) Reg Hrs Oct-22
  • Actuals(-2) Reg Hrs Nov-22
  • Actuals(-1) Reg Hrs Dec-22

For my needs, I need to rename these columns to something generic, such as:

  • Actuals(-3) Reg Hrs
  • Actuals(-2) Reg Hrs
  • Actuals(-1) Reg Hrs

This is to be able to support an upload to a pre-configured schema.

Is there a way I can use a regular expression to "select" these columns, and rename them?

Here is what I currently have:

    Import-Csv -Path $csvFile | 
        where {$_."Cost Center" -eq "ABC123"} | 
        Select-Object @{ expression={$_."Actuals(-3) Reg Hrs Oct-22"}; label='3 Months Ago Regular' } | 
        Export-Csv -notype $csvFile2

Obviously, this code example is looking for the actual column name, but I am wondering if I can use regular expressions here to match the static part. (assume there will be no ambiguity in the file)

Thanks!

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 2
    Are the columns always in the same place? You could define your headers when you import the CSV like `Import-Csv C:\Path\To\File.csv -Headers 'Name','EmployeeID','1 Month Ago Regular','2 Months Ago Regular','3 Months Ago Regular'` – TheMadTechnician Jan 27 '23 at 20:26
  • Thank you @TheMadTechnician! That worked (except it was -Header, without the plural). – AJ Mieskolainen Jan 28 '23 at 20:33

0 Answers0