If your CSV looks anything like this:
Account,Vendor,Item,Amount
001,Some Vendor,Something expensive, 1
002,Another Vendor,Something cheapish,26
you can update without a loop:
# create a lookup hashtable where you combine the account values with the wanted replacement
$lookup = @{
'001' = 'Hardware'
'002' = 'Software'
# etcetera
}
# import the csv and update the `Account` column
$Results = Import-Csv D:\Test\Expenses.csv | Select-Object @{Name = 'Account'; Expression = {$lookup[$_.Account]}}, * -ExcludeProperty Account
# display on screen
$Results
# output to (new) csv file
$Results | Export-Csv -Path D:\Test\Expenses_Updated.csv -NoTypeInformation
Result:
Account Vendor Item Amount
------- ------ ---- ------
Hardware Some Vendor Something expensive 1
Software Another Vendor Something cheapish 26
As per the comment of not2qubit some explanation about the Select-Object statement used.
Because the result should reflect all fields in the csv, where the existing field value named Account
needs to be replaced, the code uses a Calculated property to set the Account field values using whatever was stored in the lookup Hashtable.
This is done with @{Name = 'Account'; Expression = {$lookup[$_.Account]}}
Next, all other fields contained in the csv are selected unchanged using the asteriks *
.
Because we're overwriting the Accound field, but keep its name, the line ends with -ExcludeProperty Account
in order to remove the original Account field in the output.
If we don't do that, PowerShell will show an error: Select-Object : The property cannot be processed because the property "Account" already exists.