Nate
Nate

Reputation: 862

Replace One CSV Field With Another Through PowerShell

In PowerShell I'm importing a CSV SAMTemp2 which will have a field called SO. Sometimes SO will be populated with "NW" and in these cases I just want to pull the field called ProdProj from the same line and replace the data in SO with the data in ProdProj then export it the data in that condition.

$RepNW = Import-Csv $SAMTemp2
foreach($d in $data){
If($d.SO -eq "NW"){($d.SO).Replace($d.ProdProj)}}
$RepNW | Export-Csv $SAMTemp -NoTypeInformation

I don't get an error, but this doesn't seem to do anything, either. Can anyone assist me, please?

Update

Per Matt below, I tried:

$RepNW = Import-Csv $SAMTemp2
foreach($d in $RepNW){
If($d.SO -eq "NW"){$d.SO = ($d.SO).Replace($d.ProdProj)}}
$RepNW | Export-Csv $SAMTemp -NoTypeInformation

But I'm not seeing any change. Any assistance is appreciated.

Upvotes: 0

Views: 76

Answers (1)

BenH
BenH

Reputation: 10034

As LotPings pointed out in this line foreach($d in $data){, you haven't defined $data and it seems that you mean it to be foreach($d in $RepNW){

Secondly, rather than using Replace() you can just set one property to be equal to the other.

Last, this probably easiest to do all in the pipeline with ForEach-Object

Import-Csv $SAMTemp2 | ForEach-Object {
    If($_.SO -eq "NW"){
        $_.SO = $_.ProdProj
    }
    $_
} | Export-Csv $SAMTemp -NoTypeInformation

Upvotes: 3

Related Questions