PowerShell Search and Replace text in a file

PowerShell Logo

Sometimes is can be handy to search a string or character in a text or log file and replace it with something else, most modern text editors do support functions like search and replace but is this possible to achieve this with PowerShell? Absolutely!

Not long ago I was developing a script that queried data out of a database and saved the query result to a CSV file only issue was that in Swiss regionale/culture the separator for CSV is the semicolon and not the comma so while I could edit the file manually with a text editor I wanted the process to be fully automated so I used PowerShell to search and replace the commas with semicolon in place here’s how.

# PowerShell search and replace character in a file

Get-Content $file01 | ForEach-Object -Process {$_ -replace ',',';'} | Set-Content $file01

As you see implementing PowerShell search and replace is a matter of using a single line, the above example will search and replace within the same file if you want to write output to a different output you would use something like this:

# PowerShell search and replace writing changes to a new file

Get-Content $file01 | ForEach-Object -Process {$_ -replace ',',';'} | Set-Content $newFile

You can even turn this into a simple function to call within the script which is useful if you want PowerShell to search and replace into multiple files like this:

# PowerShell Search and replace function in script

Function Format-Csv()
{
    foreach ($csv in $fileDir) 
    {
        (Get-Content $csv) |
        ForEach-Object -Process {
            $_ -replace ',', ';'
        } |
        Set-Content $csv
    }
} # End Format-Csv Function definition

Do you use or know any other way to replace characters or strings with PowerShell? Leave a comment below to share the knowledge!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s