PowerShell Find and Replace in File

Finding and replacing a file is a very common requirement in automation. In this PowerShell tutorial, I will explain in detail how to find and replace in a file using PowerShell and also I will show how to replace a line in a file using PowerShell.

To find and replace text in a file using PowerShell, you can use the -replace operator with a regular expression for pattern matching or the .Replace() method for simple text replacement. For example, use $content = Get-Content ‘file.txt’; $content = $content -replace ‘oldText’, ‘newText’; Set-Content ‘file.txt’ -Value $content to read, replace, and write back to the file.

Find and Replace in File using PowerShell

Now, let us check out various methods to find and replace in a file using PowerShell.

1. Using the -replace Operator

The -replace operator is one of the simplest ways to perform a string replacement in PowerShell. This operator uses a regular expression (regex) on the left side to match the text you want to replace and the replacement text on the right side.

Here is a complete PowerShell script:

$content = Get-Content -Path "C:\MyFolder\file.txt"
$content = $content -replace 'oldText', 'newText'
Set-Content -Path "C:\MyFolder\file.txt" -Value $content

In this example, Get-Content reads the file’s content, -replace updates the text, and Set-Content writes the modified content back to the file.

You can see the output in the screenshot below after I executed the PowerShell script using VS code.

PowerShell Find and Replace in File

2. Find and Replace in File in PowerShell Using the .Replace() Method

Another method for replacing text is using the .Replace() method, which is a case-sensitive method of the string object in PowerShell. Unlike the -replace operator, this method does not use regex, so it’s suitable for simple and direct text replacements.

Here is an example

$content = Get-Content -Path "C:\MyFolder\file.txt" -Raw
$content = $content.Replace('oldText', 'newText')
Set-Content -Path "C:\MyFolder\file.txt" -Value $content

The -Raw parameter ensures that Get-Content retrieves the file content as a single string, allowing the .Replace() method to operate on the entire file content at once.

3. Using PowerShell Functions

You can also create a custom PowerShell function to encapsulate the find and replace logic. This approach provides better reusability and can be extended with additional features like logging or error handling.

Here is a PowerShell function that you can reuse for finding and replacing in a file.

function FindAndReplaceInFile {
    param (
        [string]$Path,
        [string]$OldText,
        [string]$NewText
    )

    try {
        (Get-Content -Path $Path) -replace $OldText, $NewText | Set-Content -Path $Path
    }
    catch {
        Write-Error "An error occurred: $_"
    }
}

FindAndReplaceInFile -Path "C:\MyFolder\file.txt" -OldText 'oldText' -NewText 'newText'

This custom function FindAndReplaceInFile takes the file path, the text to find, and the text to replace as parameters, performing the find and replace operation within a try-catch block to handle potential errors gracefully.

4. Find and Replace with Multiple Files

If you want to find and replace across multiple files, you can combine PowerShell’s file manipulation cmdlets with the replacement methods.

Here is a complete example.

Get-ChildItem -Path "C:\MyFolder\*.txt" -Recurse | ForEach-Object {
    $content = Get-Content -Path $_.FullName -Raw
    $content = $content -replace 'oldText', 'newText'
    Set-Content -Path $_.FullName -Value $content
}

This script uses Get-ChildItem to retrieve all .txt files in the specified directory and its subdirectories, then iterates over each file with ForEach-Object, performing the replacement and saving the changes.

5. Find and Replace with Regular Expressions

For more advanced text manipulation, you can use PowerShell regular expressions. Regex allows you to match patterns and use capture groups to perform sophisticated find and replace operations.

Here is an example.

$content = Get-Content -Path "C:\MyFolder\file.txt" -Raw
$pattern = '(\d{4})-(\d{2})-(\d{2})'
$replacement = '$3/$2/$1'
$content = $content -replace $pattern, $replacement
Set-Content -Path "C:\MyFolder\file.txt" -Value $content

In this example, the regex pattern (\d{4})-(\d{2})-(\d{2}) matches dates in the format YYYY-MM-DD and the replacement string $3/$2/$1 rearranges the date to DD/MM/YYYY.

Replace Line in File using PowerShell

When working with text files in Windows, you might get requirements like replacing lines in files. In this tutorial, we’ll explore various methods to replace a line in a file using PowerShell.

Here are a few examples.

1. Using the -Replace Operator

One of the simplest ways to replace text in PowerShell is by using the -Replace operator. This operator allows you to specify a pattern to match and a string to replace it with.

Here is an example.

# Define the path to your file
$filePath = 'C:\MyFolder\file.txt'

# Read the file content
$content = Get-Content $filePath

# Replace the target line
$content = $content -Replace 'old line text', 'new line text'

# Write the updated content back to the file
$content | Set-Content $filePath

This PowerShell script reads the content of the specified file, replaces occurrences of ‘old line text’ with ‘new line text’, and writes the updated content back to the file.

2. Using the .Replace() Method

Another way you can replace a line in file using PowerShell is by using the .Replace() method, which is a part of string objects in PowerShell. This method is case-sensitive and replaces exact matches of the string.

Here is a complete example.

# Define the path to your file
$filePath = 'C:\MyFolder\file.txt'

# Read the file content
$content = Get-Content $filePath

# Replace the target line using the .Replace() method
$content = $content.Replace('This is the first line', 'This is the replaced line')

# Write the updated content back to the file
Set-Content -Path $filePath -Value $content

This method works similarly to the -Replace operator, but it’s important to note that it only replaces the first occurrence of the string.

3. Using Regular Expressions

This is the 3rd method; you can use regular expressions. PowerShell’s -Replace operator supports regex, allowing you to match patterns rather than fixed text.

Here is an example.

# Define the path to your file
$filePath = 'C:\MyFolder\file.txt'

# Define your regex pattern
$pattern = 'some\s+regex pattern'

# Define the replacement text
$replacement = 'replacement text'

# Read the file content
$content = Get-Content $filePath

# Replace the target line using regex
$content = $content -Replace $pattern, $replacement

# Write the updated content back to the file
Set-Content -Path $filePath -Value $content

In this script, $pattern holds the regular expression to match the line you want to replace, and $replacement is the new text you want to use.

4. Using Conditional Replacement with Foreach-Object

Sometimes, you may want to replace a line only if it meets certain conditions. You can use the Foreach-Object cmdlet in combination with -Replace to achieve this in PowerShell.

Look at the below complete example.

# Define the path to your file
$filePath = 'C:\MyFolder\file.txt'

# Define the condition for replacement
$condition = 'specific start of the line'

# Define the replacement text
$replacement = 'entire new line text'

# Read the file content and replace lines conditionally
(Get-Content $filePath) | Foreach-Object {
    if ($_ -match $condition) {
        $_ -Replace $_, $replacement
    } else {
        $_
    }
} | Set-Content $filePath

This script reads each line of the file and checks if it matches the specified condition. If it does, the line is replaced; otherwise, it remains unchanged.

Conclusion

In this tutorial, I explained how to find and replace in a file in PowerShell using various methods like -replace operator and .replace() method.

I have also explained to you how to find and replace in multiple files in PowerShell. And how to replace a line in a file using PowerShell.

Remember to always backup your files before performing bulk replacements to prevent accidental data loss.

You may also like the following tutorials:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.