new--Find & Replace in Files with PowerShell

Find and Replace text in all selected files in a folder.

Script

PowerShell
$SPath = 'D:\DataSelf\PowerShell\*.csv'     # Edit path
$FindStr    = 'xx'                          # Edit find & replace values
$ReplaceStr = "yy"
#-----------------------------------------------
Write-host "Search Path: $SPath"
Write-Host "  Find: $FindStr    Replace: $ReplaceStr "
Write-Host "-----------------------------------"
Write-Host "Files to search in $SPath"
$files = Get-ChildItem -Path $SPath  -verbose
foreach ($file in $files) {
   write-host $file.fullname
}
Write-Host "Start Find & Replace"
$files = Get-ChildItem -Path $SPath 
foreach ($file in $files) {
    if (Select-String -Path $file -Pattern $FindStr -verbose -list)  {
        write-host "Selected file : $file"  
        # Read & Display the contents of the file before Find/Replace
        $content = Get-Content -Path $file
        Write-Output $content
        Write-Host ""
        # Perform the replacement
        #>> $updatedContent = $content -replace $FindStr, $ReplaceStr  # Regular Expressions
        $updatedContent = $content.Replace($FindStr, $ReplaceStr)  # Simple string replacement
        $updatedContent | Set-Content -Path $file
         # Read & Display the contents of the file AFTER Find/Replace
        $content = Get-Content -Path $file.FullName
        Write-Host "After Find/Replace"
        Write-Output $content
        Write-Host ""
    }
}Lines 1 - 3:  Replace the literals with your search values.

Instructions:

Lines 1 - 3: Replace the literal strings with your file, find and replace values.

:info:

Only updates files that match the criteria in the $SPath and $FindStr variables.


Find & Replace Case In-sensitive

.Replace Method

$newContent = $content.Replace("hello", "Hi", [StringComparison]::OrdinalIgnoreCase)

Using the Replace() method with StringComparison.OrdinalIgnoreCase: The Replace() method allows you to specify a StringComparison parameter to control the comparison behavior. By setting it to OrdinalIgnoreCase, you can perform a case-insensitive replacement.

The .Replace method is an older method that doesn’t work in some contexts.

-ireplace Operator

  1. Using the -ireplace operator: The -ireplace operator is similar to the -replace operator, but it performs a case-insensitive replacement. Here's an example:

   $content = "Hello World"
   $newContent = $content -ireplace "hello", "Hi"

Alternative Method for Simple Text (no regular expressions)

Get-ChildItem -Path "C:\folder" -File |
ForEach-Object {
    $content = Get-Content -Path $_.FullName
    $newContent = $content.Replace("Dev", "Demo")
    Set-Content -Path $_.FullName -Value $newContent
}

Here's a breakdown of the script:

  1. Use the Get-ChildItem cmdlet to retrieve all the files within the specified folder (C:\folder) using the -File parameter to exclude directories.

  2. Iterate over each file using the ForEach-Object cmdlet.

  3. Use the Get-Content cmdlet to read the content of each file and store it in the $content variable.

  4. Use the Replace() method to find and replace the desired text in the $content variable.

  5. Use the Set-Content cmdlet to write the modified content back to the original file.

This script performs the find and replace operation without using the -replace operator. Instead, it leverages the Replace() method available on string objects in PowerShell.

Note: The Replace() method performs a case-sensitive replacement. If you need a case-insensitive replacement, you can use the -replace operator instead.

Alternative Method

PowerShell
Get-ChildItem -Path "C:\folder" -Filter "*.txt" -Recurse | ForEach-Object {
    (Get-Content $_.FullName) -replace "oldtext", "newtext" | Set-Content $_.FullName
}

Here's how the script works:

  1. Get-ChildItem is used to retrieve all the files in the specified folder (C:\folder) with the .txt extension. The -Recurse parameter is used to search for files in subdirectories as well.

  2. The resulting file objects are passed through the pipeline to the ForEach-Object cmdlet.

  3. Within the ForEach-Object block, Get-Content is used to read the content of each file.

  4. The -replace operator is used to find and replace the specified text (oldtext) with the new text (newtext). The -replace operator uses regular expressions. Some find and replace values may be misinterpreted as regular expressions.

  5. The modified content is then written back to the file using Set-Content.

This script will iterate through all the files in the specified folder (including subdirectories) with the .txt extension and replace the specified text in each file.

Regular Expressions