Powershell Find and Replace a string in the file

Posted: October 22, 2015 in PowerShell

Search for a string and replace value after equals sign

Lets say i have a file ABC.prm with the below contents

I have to update the $$MAX_POST_DT value with a new value present in another file say DATE_FILE.TXT with the below data

Below is the script to achieve the above requirement.
 $filepath=$args[0]        # Pass the Actual file in our case its ABC.prm
 $DateFile=$args[1]        # pass the date file in this case it is DATE_FILE.TXT
$filepath_BKP = $filepath.split('.')[0] + "_BKP.prm"
foreach($L in $orig_param)
 if($L -match 'MAX_RI_POST_DT=*')
 $L -replace '(\d{1,8})',$eff_dt | Out-File -append -NoClobber $filepath_BKP
 $L | Out-File -append -NoClobber $filepath_BKP
 }#Remove the actual file and rename the BKP file below
If(Test-Path "$filepath")
 { # remove the file below.
 Remove-Item "$filepath"
 Write-host "The input file is deleted."
# Rename the file below
 Rename-Item -Path $filepath_BKP -NewName $filepath
 Write-host "The output body file is renamed as the input file name."

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