Powershell to change text in csv file

2

Hello All,

While writing one of the scripts in Powershell, I came across a requirement where I had to change the data that I had exported to a .csv file.

The reason I chose this because there was no built in Powershell way that I could replace one of the columns.

Anyways, lets get to the code.

Assume that you have a csv file called reports.csv in the C folder of your machine. And you want to change the text pool to display

$lines = Get-Content C:\reports.csv
$newlines = foreach ($line in $lines){
$line -replace 'pool' , 'display'
}
Set-Content reports.csv $newlines

So what did we do here.

First we got the content from the csv file and set it to a variable called $lines

Then we set another variable called $newlines and ran a for loop asking it to check every line and change the text 'pool' to 'display'.

After that we just updated the values that were saved in the variable $newlines with the help Set-Content to the repots.csv file.

Pretty simple eh?

Hope this was informative and Happy scripting!

Share.

About Author

I am Adil Arif, working as a Senior Technical Support Engineer at Rubrik as well as an independent blogger and founder of Enterprise Daddy. In my current role, I am supporting infrastructure related to Windows and VMware datacenters.

2 Comments

  1. Would wildcards work with this?

    Eg would -replace ‘pool*’ , ’display’

    Then change “pool float” and “pool car” and “pool anything” to “display”?

Leave A Reply