PowerShell - Select-Object when the column header has a dynamic name

197 Views Asked by At

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!

0

There are 0 best solutions below