Home > Software engineering >  Add column to CSV with formatting
Add column to CSV with formatting

Time:12-21

I have a small csv with 3 columns.

Date        Time    Event
12/19/2021  9:00am  Low
12/19/2021  7:30am  Medium
12/20/2021  9:00am  Low

I want to add a 4th column with header of Warning. In the 4th column I want to subtract 15 minutes from column

Date        Time    Event   Warning
12/19/2021  9:00am  Low     8:45am
12/19/2021  7:30am  Medium  7:15am
12/20/2021  9:00am  Low     8:45am

Im having difficulty with the formatting?.

Thank you for your time today.

CodePudding user response:

You can use a calculated property on Select-Object to calculate the time difference, however this would leave the Date column intact.

# Use $Csv = Import-Csv path/to/csv.csv here instead
$csv = @'
Date        Time    Event
12/19/2021  9:00am  Low
12/19/2021  7:30am  Medium
12/20/2021  9:00am  Low
'@ -replace '  ',',' | ConvertFrom-Csv

$csv | Select-Object *, @{
    Name = 'Warning'
    Expression = {
        ([datetime]$_.Time).AddMinutes(-15).ToShortTimeString()
    }
}

Results in:

Date       Time   Event  Warning
----       ----   -----  -------
12/19/2021 9:00am Low    8:45 AM
12/19/2021 7:30am Medium 7:15 AM
12/20/2021 9:00am Low    8:45 AM
  • Related