rcubefather rcubefather - 3 months ago 12
PowerShell Question

How to search for a string and replace entire line using powershell? (If string NOT matched, need to create a new line with the content)

Sample.txt:

SQL.test = True
wer.vul = 1
temp_RTE = False
user_admin = no


In the above text file, I want to search for a string
"test"
and replace entire line with
"SQL.test = False"
using Windows Powershell script. If
"test"
text is not matched, need to add
"SQL.test = False"
line to that file.

I have tried this. But I am unable to solve.

Please guide me how to achieve this.

Answer

One way to do it is as follows:

$text = 'test'
$found = $false
$infile = '.\a.txt'
$outfile = '.\b.txt'
Get-Content -Path $infile | % { 
    if ($_ -match $text)
    {
        $found = $true
        "SQL.test = False"
    }
    else
    {
        $_
    }
} | Out-File -filepath $outfile
if (!$found)
{
    "SQL.test = False" |Out-File -filepath $outfile -Append
}

This can be optimized further, I'm sure.

Basically what this does is use Get-Content to retrieve each line in the text file, and pipe them to Select-String. If the text is found, the line is changed, if not, the original line is returned. If the text is not found, then it's appended.

If the text is found the output is:

SQL.test = False
wer.vul = 1 
temp_RTE = False 
user_admin = no 

else

wer.vul = 1 
temp_RTE = False 
user_admin = no 
SQL.test = False