Search code examples
powershellcsvforeach

Foreach loop in PowerShell issue


Someone please help me with my script. I have an existing csv file that just has one column and two rows under it as followed:

Yesterday
77
22

I want to just add a new column for todays date with the values as per the variables i set. The outcome should look like:

Yesterday 01-03-2024
77 100
22 200

But instead, I get:

Yesterday 01-03-2024
77 100
22 100

I am a bit new to powershell still and unsure how to open an array to add $newvalue1 to just the first row and $newvalue2 to just the second row.

# Set the path to the existing CSV file
$csvPath = "C:\path\to\existing\file.csv"

# Import the CSV file
$data = Import-Csv -Path $csvPath

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

$Newvalue1 = "100"
$Newvalue2 = "200"

# Add a new column to the data with today's date as the column name
foreach ($row in $data) {
    $row | Add-Member -MemberType NoteProperty -Name $newColumnName -Value $Newvalue1
}



# Export the updated data to the CSV file
$data | Export-Csv -Path $csvPath -NoTypeInformation

Solution

  • Change the 2 variables:

    $Newvalue1 = "100"
    $Newvalue2 = "200"
    

    To an array:

    $NewValues = @(
        "100"
        "200"
    )
    

    Then you can append new values to your collection by indexing:

    $data = @'
    Yesterday
    77
    22
    '@ | ConvertFrom-Csv
    
    $newColumnName = Get-Date -Format 'yyyy-MM-dd'
    $index = 0
    $NewValues = @(
        '100'
        '200'
    )
    
    foreach ($row in $data) {
        $row | Add-Member -MemberType NoteProperty -Name $newColumnName -Value $Newvalues[$index++]
    }
    
    $data
    

    Another alternative is to use the same logic but creating new objects instead of updating them with Select-Object and a calculated property:

    $data = @'
    Yesterday
    77
    22
    '@ | ConvertFrom-Csv
    
    [string] $newColumnName = Get-Date -Format 'yyyy-MM-dd'
    $index = @{ Value = 0 }
    $NewValues = @(
        '100'
        '200'
    )
    
    $data | Select-Object *, @{ N = $newColumnName; E = { $NewValues[$index.Value++] }}