Home > Enterprise >  Copy values from existing CSV column and add to new column with PowerShell
Copy values from existing CSV column and add to new column with PowerShell

Time:12-08

I have a CSV with 4 Columns. I am trying to copy values from the costs column to the corpcosts columns based on values from the department number column. Basically, any cost with department number starting with 8* to be moved or copied to the corpcost column.

For reference:

Original:

Employee ID OwnerEmail DepartmentNumber Costs
fg345 [email protected] 8894 4654.45
78f54 [email protected] 3453 4994.15

Expectation:

Employee ID OwnerEmail DepartmentNumber Costs CorpCosts
fg345 [email protected] 8894 4654.45 4654.45
78f54 [email protected] 3453 4994.15

I have tried using a foreach loop, but I must admit I am fairly new to PowerShell and learning as I go. The code I have tried thus far is as follows:

$corpcosts= foreach($corpcost in $CSVImport.corpcosts){
        if($CSVImport.DepartmentNumber -eq "8*"){
            $CSVImport.DepartmentNumber   $CSVImport.Costs 
        }
    }
           
$CSVImport|Select-Object *, @{N= 'CorpCosts'; E={$corpcosts[$_.CorpCosts]}} |Export-Csv "$Env:temp/$OutputFile" -NoTypeInformation 

CodePudding user response:

The Expression only needs a few changes to add an if statement to check for departments starting with the number 8, and if true, fill with the Costs column into the new CorpCosts column.

$CSVImport = Import-Csv Costs.csv
$CSVImport|Select-Object *, @{N= 'CorpCosts'; E={if($_.DepartmentNumber -like '8*'){$_.Costs}}} | Export-Csv "$Env:temp/$OutputFile" -NoTypeInformation 

CodePudding user response:

You can do it with just one calculated property, for the comparison you could either use .StartsWith or a Matching Operator of your choice (either -like '8*' or -match '^8'), not that equality operators are not aware of wildcard characters (*).

Import-Csv path\to\source.csv |
    Select-Object *, @{N='CorpCosts';E={ if($_.DepartmentNumber.StartsWith('8')) { $_.Costs } }} |
    Export-Csv path\to\output.csv -NoTypeInformation
  • Related