PowerShell provides several ways to replace strings inside files using the standard verb-noun CmdLet pairs Get-Content and Set-Content, plus the -replace operator.

How the One-Liner Works

(Get-Content -Path "C:\temp\log.txt") -replace "192.168.1.1", "10.0.0.5" | Set-Content -Path "C:\temp\log.txt"
  1. Get-Content reads the file and returns content (an array of strings by default; one string per line).
  2. Parentheses () force PowerShell to evaluate Get-Content first, producing the value that the -replace operator acts on. Parentheses are needed for operator precedence, not to convert to string.
  3. The -replace operator searches each element and replaces matches.
  4. Set-Content writes the modified content back to the file.

Parentheses are necessary because -replace is an operator, not a parameter of Get-Content. Without (), PowerShell would try to bind -replace to Get-Content and report that it is not a valid parameter.

What -replace Is

-replace is a PowerShell comparison operator that performs regular-expression substitution. It works on strings and arrays of strings.

Operator Meaning
-replace Case-insensitive regex replacement (default)
-creplace Case-sensitive regex replacement
-ireplace Explicit case-insensitive regex replacement

Because -replace uses regex, special characters like . \ $ * need escaping if you intend a literal match (see below).

Read as a Single String

For patterns that may span multiple lines, use the -Raw switch:

(Get-Content -Path "C:\temp\log.txt" -Raw) -replace "Start.*?End", "REDACTED" | Set-Content -Path "C:\temp\log.txt"

-Raw returns the entire file as one string instead of an array of lines, so -replace can match across line boundaries.

Replace Across Multiple Files

Get-ChildItem -Path "C:\temp\*.txt" | ForEach-Object {
    (Get-Content -Path $_.FullName -Raw) -replace "oldString", "newString" |
    Set-Content -Path $_.FullName
}

Regex vs. Literal Text

-replace uses regular expressions by default. To treat the search text as a literal string, escape it with [regex]::Escape():

$old = [regex]::Escape("C:\Windows\System32")
(Get-Content -Path "file.txt" -Raw) -replace $old, "C:\NewPath" | Set-Content -Path "file.txt"

Useful Tips

  • -replace applies to string content (or arrays of strings). It is not useful for binary files because it expects string data.
  • -replace is case-insensitive by default; use -creplace for case-sensitive replacement.
  • Always back up files before running bulk replacements, especially during Digital Forensics or Incident Response work.
  • These commands are ideal for experimenting in the PowerShell ISE Direct Command Entry Panel before saving them into a script.