1

I have a script that should look in a CSV file and modify it. My file looks like this:

"mydata","module1","module2","module3","module4","module5"
"kk-ll","module1","","module3","",""
"kk-pp","module1","","module3","",""  

In case the data in column mydata exists: modify value in column $Module.
In case it does not exist: add a new line to the file.

The code I wrote for the fist part is OK, for the second part (updating the file) it's not working.

$ExistingCSV = Import-Csv MyCsv.csv
if ($ExistingCSV.mydata -eq "$LOT-$WID") {
    $ExistingCSV | ForEach-Object {
        if ($_.mydata -eq "$LOT-$WID") {
            $_.$Module = $Module
        }
    }

    $ExistingCSV | Export-Csv $ProgressLogPath\$LOT.csv -NoTypeInformation
} else {
    $ExistingCSV.mydata = "$LOT-$WID"
    $ExistingCSV.$Module = $Module
    Add-Content $ExistingCSV -Value $_.Lot_WaferID $_.$Module $_.ScriptLogPath

    $ExistingCSV | Export-Csv $ProgressLogPath\$LOT.csv -NoTypeInformation
}

1 Answer 1

2

I would use -contains instead of -eq, but since PowerShell operators work as enumerators the latter should work too in your case.

If a match is found, modify the existing data and export the result back to the CSV. Otherwise all you need to do is create a custom object with the data you want to add, and append that to the CSV.

$csv = 'C:\path\to\your.csv'

$ExistingCSV = Import-Csv $csv
if ($ExistingCSV.mydata -contains "$LOT-$WID") {
    foreach ($row in $ExistingCSV) {
        if ($row.mydata -eq "$LOT-$WID") {
            $row.$Module = $Module
        }
    }
    $ExistingCsv | Export-Csv $csv -NoType
} else {
    $obj = New-Object -Type PSObject -Property @{
        'mydata'  = "$LOT-$WID"
        'module1' = $null
        'module2' = $null
        'module3' = $null
        'module4' = $null
        'module5' = $null
    }
    $obj.$Module = $Module
    $obj | Export-Csv $csv -NoType -Append
}

Replace $null with whatever value the moduleX fields are supposed to have.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your answer. it is OK but not complete. my parameters are mydata and module name so how can know which module to update? in one occasion it can be module1 and in the second module2
great! it works fine but i need to add the new created $obj the existing csv file. is it possible to combine array with existing CSV? in addition, the csv created will loose the order of the csv of the original file.
@yuvalr What are you talking about? The code I posted will either update the matching record(s) of the given CSV, or append a new record to it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.