0

I am trying to replace a line in a CSV and retain the array structure, see CSV and code example:

CSV example:

Computer,Domain
DC001,contoso.local
DB001,contoso.local
AB001,contoso.local

Code:

[array]$csv= Import-Csv c:\docs\MyCsv.csv
$newCSv = $csv | ForEach { $_.Domain -replace "contoso", "MyDomainName" }

Output of $newCsv:

MyDomainName.local
MyDomainName.local
MyDomainName.local

Desired output $newCsv:

 Computer Domain       
-------- ------       
DC001    MyDomainName.local
DB001    MyDomainName.local
AB001    MyDomainName.local

I have tried piping to| Select Computer, Domain but this does not work. Is there a way to fix this?

1
  • the output you show is the DISPLAY of the variable content. if you want it converted to a CSV format you need to use Export-CSV. Commented Oct 14, 2020 at 14:13

2 Answers 2

2

You are not modifying your csv at all, check the output of your command before assigning it to a variable.

$csv = @'
Computer,Domain
DC001,contoso.local
DB001,contoso.local
AB001,contoso.local
'@ | ConvertFrom-Csv

$csv | foreach {$_.domain -replace 'contoso','MyDomainName'}

MyDomainName.local
MyDomainName.local
MyDomainName.local

You are assigning that output to variable $newcsv which has no bearing on the contents of $csv. If you want to replace text in one of your properties, you need to do just that.

$csv | foreach {$_.domain = $_.domain -replace 'contoso','MyDomainName'} # No output

Having assigned the replaced text from property .domain back into .domain now take a look at the contents of $csv

$csv

Computer Domain            
-------- ------            
DC001    MyDomainName.local
DB001    MyDomainName.local
AB001    MyDomainName.local

Now you can export it

$csv | Export-Csv $somefile -NoType
Sign up to request clarification or add additional context in comments.

Comments

2

To output the new CSV, you need to specify its properties. To change the values in just one column, you can use Select-Object with a calculated property:

$newCsv = Import-Csv -Path 'D:\Test\MyCsv.csv' | 
          Select-Object Computer, 
                        @{Name = 'Domain';Expression = {$_.Domain -replace "contoso", "MyDomainName" }}

#output on screen
$newCsv

# write to new csv file
$newCsv | Export-Csv -Path 'D:\Test\MyNewCsv.csv' -NoTypeInformation

Output

Computer Domain            
-------- ------            
DC001    MyDomainName.local
DB001    MyDomainName.local
AB001    MyDomainName.local

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.