Search code examples
powershellcsvforeach

Adding a new row in existing column powershell


I have a csv file with three columns like the following:

Date Active Inactive
1/14/24 200 300
1/15/24 250 350

I am trying to add a new row for each of the three columns while keeping all the previous values. The new row must be using get-date for the current date and the "active" value is 400 and "inactive" value 500.

Below I have a script that is similar but only adds a new column (not the row to the existing column). Any help on modifying this script to add a new row with the requested values with only the existing column is much appreciated!

# Get today's date in the desired format for the new column name
$NewColumnName = Get-Date -Format 'yyyy-MM-dd'

# Import the CSV file AND add an empty "date" column
$Data = Import-Csv -Path $CsvPath | Select-Object -Property Date, @{n = "$newColumnName"; e = { $null } }

# array of the values you want to add.
# you could add each by themselves but this scales better if you go beyond a few rows
$NewValues = @(
    '400'
    '500'
)

# setting up the index variable
$LoopIndex = 0

# cycle through the elements in `$data`
$Data | ForEach-Object {
    # `$_` is the name for the object of the current iteration of the loop
    $_.$NewColumnName = $NewValues[$LoopIndex++]
}

##EXPORT # Get today's date in the desired format for the new column name
$NewColumnName = Get-Date -Format 'yyyy-MM-dd'

# Import the CSV file AND add an empty "today" column
$Data = Import-Csv -Path $CsvPath | Select-Object -Property Date, @{n = "$newColumnName"; e = { $null } }

# array of the values you want to add.
# you could add each by themselves but this scales better if you go beyond a few rows
$NewValues = @(
    '400'
    '500'
)

# setting up the index variable
$LoopIndex = 0

# cycle through the elements in `$data`
$Data | ForEach-Object {
    # `$_` is the name for the object of the current iteration of the loop
    $_.$NewColumnName = $NewValues[$LoopIndex++]
}

##EXPORT 

Solution

  • All you need is the Export-Csv cmdlet with -Append:

    $value = [PSCustomObject]@{
        Date = Get-Date -Format 'M/d/yy'
        Active = 400
        Inactive = 500
    }
    $value | Export-Csv -Path $CsvPath -Append -NoTypeInformation