Replace string in multiple files in powershell

@Navya_Budagam

I hope this is what you are looking for

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

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

$modifiedfiles | Out-String -Stream

Cheers

Hi @Anil_G
How come this resolves the previous issue of accepting filenames which contains special characters?

Able to update multiple string values but getting below error for the file which has special characters.

Get-Content : An object at the specified path
C:\Users\Desktop\PowerShell\utility+team+[old±+retired+7%2f15%2f2016].txt does not exist, or has been filtered
by the -Include or -Exclude parameter.
At line:11 char:20

  •     $content = Get-Content $_.FullName
    
  •                ~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : ObjectNotFound: (System.String:String) [Get-Content], Exception
    • FullyQualifiedErrorId : ItemNotFound,Microsoft.PowerShell.Commands.GetContentCommand

@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

Hi @Anil_G - This solution is working fine without any issues. I will apply this logic on a broader file system and get back to you if I see any issues :slight_smile:

I appreciate the time and effort you invested to help on this. Thank you for your continuous effort.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.