PS Script for replacing strings in the File


If you have a requirement to replace particular string in a file with some other string, it can be done using below PS statements.

(Get-Content .\test.txt | ForEach-Object {$_ -replace "CurrentUser","CurrentUser2"}) | Set-Content .\test.txt

Explanation –

1. First step is to read the content of the file

2. Pipe the output. Read each line by line and replace the required value. Note – “$_” means this row. It is equivalent to “this.” in .Net.

3. Please note “(“and “)” at the start of first command and end of second command respectively. It is needed as we want to send (Pipe) the full output to the last statement to set the content.

4. Finally set the updated content to the same file.

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