Replace string in multiple files in powershell

@Navya_Budagam

My Bad…I have modified the old one…please check this

$directory = "C:\Users\Desktop\powershell"
$searchpattern = "*.*"
$oldstring1 = 'runAs="India"'
$newstring1 = 'runAs="America"'
$oldstring2 = 'runAsGuid="India"'
$newstring2 = 'runAsGuid="America"'
$modifiedfiles = @()

Get-ChildItem -LiteralPath $directory -Include $searchpattern -Exclude *.atr -Recurse | ForEach-Object {
    if($_.GetType().Name -eq "FileInfo") {
        $content = Get-Content -LiteralPath $_.FullName
        if($content -match $oldstring1 -or $content -match $oldstring2) {
            $modifiedcontent = $content -replace [regex]::Escape($oldstring1), $newstring1 -replace [regex]::Escape($oldstring2), $newstring2
            Set-Content -LiteralPath $_.FullName $modifiedcontent
            $modifiedfiles += $_.FullName
        }
    }
}

$modifiedfiles | Out-String -Stream

cheers

1 Like