Helper function to replace data in a CSV file

Just a quick share as I needed this for something, this function will replace values in a CSV file. It takes the desired column(s) and value(s) to search for and a new value and desired target column as required parameters.

function update-csvColumn{
    Param(
        [Parameter(Mandatory=$true)]$csvContents, #input original CSV file contents here (use import-csv first)
        [Parameter(Mandatory=$true)][Array]$searchForColumns, #names of the columns you want to base your search on
        [Parameter(Mandatory=$true)][Array]$searchForValues, #replace rows in $searchForColumn that match these values (in same order!)
        [Parameter(Mandatory=$true)]$replaceColumn, #set this column to what you specified in $newValue
        [Parameter(Mandatory=$true)]$newValue #the new value you wish to set $searchForColumn or $replaceColumn to
    )
    if($searchForColumns.Count -ne $searchForValues.Count) {Throw "You must supply an equal number of columns and values to match on"}
    for($i = 0; $i -lt $csvContents.Count; $i++){
        $replace = $True
        for($c = 0; $c -lt $searchForColumns.Count; $c++){
            if($csvContents[$i].$($searchForColumns[$c]) -ne $searchForValues[$c]){
                $replace = $False
            }
        }
        if($replace){
            $csvContents[$i].$replaceColumn = $newValue
        }
    }
    return $csvContents
}

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Raj Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
Raj
Guest
Raj

I am using OnedriveMapper script to map my J: drive with One Drive for business, when I run it in windows server 2012 r2 getting this error -ERROR | ERROR: detected string error 224 in return code of net use command, this usually means your trusted sites are mi sconfigured or KB2846960 is missing or Internet Explorer needs a reset ERROR | failed to contact J: after mapping it to \\nycdohmhwintel-my.sharepoint.com@SSL\DavWWWRoot\personal\rgundimeda_n ycdohmhwintel_onmicrosoft_com\Documents, check if the URL is valid. Error: System error 224 has occurred. Access Denied. Before opening files in this location, you must first add the web site to… Read more »