ghw

# Define the parameters
$SearchPath = "." # '.' means the current directory. Change to a path like 'C:\MyFiles\' if needed.
$FileFilter = "*abcd*" # Files containing 'abcd' anywhere in the name
$OldText = 'set ab="fghfg"' # The exact string to be replaced
$NewText = " " # The replacement string (a single space)
$ModifiedCount = 0

Write-Host "Starting file search in $SearchPath for files containing '$FileFilter'..."

# 1. Use Get-ChildItem to find all files matching the name pattern
Get-ChildItem -Path $SearchPath -Filter $FileFilter -File | ForEach-Object {
    
    $FilePath = $_.FullName
    Write-Host "`n-- Processing File: $($_.Name) --"
    
    try {
        # 2. Read the entire content of the file into a single string (using -Raw)
        $Content = Get-Content -Path $FilePath -Raw

        # Check if the content contains the target string
        if ($Content -like "*$OldText*") {
            Write-Host "Found '$OldText' inside. Performing replacement..."
            
            # 3. Use the .Replace() method for a case-sensitive, literal string replacement
            # The -replace operator could also be used, but .Replace() is often cleaner for literal strings without regex.
            $NewContent = $Content.Replace($OldText, $NewText)
            
            # 4. Write the modified content back to the original file
            # This overwrites the file.
            $NewContent | Set-Content -Path $FilePath -Force
            
            $ModifiedCount++
            Write-Host "Replacement successful. File updated." -ForegroundColor Green
        }
        else {
            Write-Host "Target text not found. Skipping file."
        }

    }
    catch {
        Write-Host "An error occurred processing file '$($_.Name)': $($_.Exception.Message)" -ForegroundColor Red
    }
}

Write-Host "`n--- Operation Complete ---"
Write-Host "Total files modified: $ModifiedCount" -ForegroundColor Yellow

Reactions

Post a Comment

0 Comments