Skip to main content

PowerShell cmdlet Replaces strings in files using a regular expression. Supports multi-line searching and replacing.

#
# Replace-FileString.ps1
#
# Replaces strings in files using a regular expression. Supports
# multi-line searching and replacing.
#
# Original Written by Bill Stewart (bstewart@iname.com)
# http://windowsitpro.com/scripting/replacing-strings-files-using-powershell
#
# Enhanced:
# https://jonlabelle.com/snippets/view/powershell/replace-strings-in-files-using-powershell
#

<#
.SYNOPSIS
    Replaces strings in files using a regular expression.

.DESCRIPTION
    Replaces strings in files using a regular expression. Supports
    multi-line searching and replacing.

.PARAMETER Pattern
    Specifies the regular expression pattern.

.PARAMETER Replacement
    Specifies the regular expression replacement pattern.

.PARAMETER Path
    Specifies the path to one or more files. Wildcards are permitted. Each
    file is read entirely into memory to support multi-line searching and
    replacing, so performance may be slow for large files.

.PARAMETER LiteralPath
    Specifies the path to one or more files. The value of the this
    parameter is used exactly as it is typed. No characters are interpreted
    as wildcards. Each file is read entirely into memory to support
    multi-line searching and replacing, so performance may be slow for
    large files.

.PARAMETER CaseSensitive
    Specifies case-sensitive matching. The default is to ignore case.

.PARAMETER Multiline
    Changes the meaning of ^ and $ so they match at the beginning and end,
    respectively, of any line, and not just the beginning and end of the
    entire file. The default is that ^ and $, respectively, match the
    beginning and end of the entire file.

.PARAMETER UnixText
    Causes $ to match only linefeed (\n) characters. By default, $ matches
    carriage return+linefeed (\r\n). (Windows-based text files usually use
    \r\n as line terminators, while Unix-based text files usually use only
    \n.)

.PARAMETER Overwrite
    Overwrites a file by creating a temporary file containing all
    replacements and then replacing the original file with the temporary
    file. The default is to output but not overwrite.

.PARAMETER Force
    Allows overwriting of read-only files. Note that this parameter cannot
    override security restrictions.

.PARAMETER Encoding
    Specifies the encoding for the file when -Overwrite is used.
    Possible values are: UTF8, UTF8-BOM, ASCII, BigEndianUnicode, Unicode or UTF32.
    The default value is UTF8.

.INPUTS
    System.IO.FileInfo.

.OUTPUTS
    System.String without the -Overwrite parameter, or nothing with the -Overwrite parameter.

.EXAMPLE
    Replace-FileString.ps1 '(Ferb) and (Phineas)' '$2 and $1' Story.txt

    This command replaces the string 'Ferb and Phineas' with the string
    'Phineas and Ferb' in the file Story.txt and outputs the file. Note
    that the pattern and replacement strings are enclosed in single quotes
    to prevent variable expansion.

.EXAMPLE
    Replace-FileString.ps1 'Perry' 'Agent P' Ferb.txt -Overwrite

    This command replaces the string 'Perry' with the string 'Agent P' in
    the file Ferb.txt and overwrites the file.
#>
[CmdletBinding(
    DefaultParameterSetName = "Path",
    SupportsShouldProcess = $true)
]
param(
    [parameter(Mandatory = $true, Position = 0)] [String] $Pattern,
    [parameter(Mandatory = $true, Position = 1)] [String] [AllowEmptyString()] $Replacement,
    [parameter(Mandatory = $true, ParameterSetName = "Path", Position = 2, ValueFromPipeline = $true)] [String[]] $Path,
    [parameter(Mandatory = $true, ParameterSetName = "LiteralPath", Position = 2)] [String[]] $LiteralPath,
    [Switch] $CaseSensitive,
    [Switch] $Multiline,
    [Switch] $UnixText,
    [Switch] $Overwrite,
    [Switch] $Force,
    [String] $Encoding = "UTF8"
)
begin
{
    # Throw an error if $Encoding is not valid.
    $encodings = @("UTF8", "UTF8-BOM", "ASCII", "BigEndianUnicode", "Unicode", "UTF32")
    if ($encodings -notcontains $Encoding)
    {
        throw "Encoding must be one of the following: $encodings"
    }

    if ($Encoding -eq "UTF8")
    {
        # Creates a UTF encdoing instance without the BOM
        $encodingObject = New-Object -TypeName 'System.Text.UTF8Encoding' -ArgumentList $false
    }
    elseif ($Encoding -eq "UTF8-BOM")
    {
        $encodingObject = [Text.Encoding]::UTF8
    }
    else
    {
        $encodingObject = [Text.Encoding]::$Encoding
    }

    # Extended test-path: Check the parameter set name to see if we
    # should use -literalpath or not.
    function test-pathEx($path)
    {
        switch ($PSCmdlet.ParameterSetName)
        {
            "Path"
            {
                Test-Path $path
            }
            "LiteralPath"
            {
                Test-Path -LiteralPath $path
            }
        }
    }

    # Extended get-childitem: Check the parameter set name to see if we
    # should use -literalpath or not.
    function get-childitemEx($path)
    {
        switch ($PSCmdlet.ParameterSetName)
        {
            "Path"
            {
                Get-ChildItem $path -Force
            }
            "LiteralPath"
            {
                Get-ChildItem -LiteralPath $path -Force
            }
        }
    }

    # Outputs the full name of a temporary file in the specified path.
    function get-tempname($path)
    {
        do
        {
            $tempname = Join-Path $path ([IO.Path]::GetRandomFilename())
        }
        while (Test-Path $tempname)

        return $tempname
    }

    # Use '\r$' instead of '$' unless -UnixText specified because
    # '$' alone matches '\n', not '\r\n'. Ignore '\$' (literal '$').
    if (-not $UnixText)
    {
        $Pattern = $Pattern -replace '(?<!\\)\$', '\r$'
    }

    # Build an array of Regex options and create the Regex object.
    $opts = @()
    if (-not $CaseSensitive) { $opts += "IgnoreCase" }
    if ($MultiLine) { $opts += "Multiline" }
    if ($opts.Length -eq 0) { $opts += "None" }
    $regex = New-Object Text.RegularExpressions.Regex $Pattern, $opts
}

process
{
    # The list of items to iterate depends on the parameter set name.
    switch ($PSCmdlet.ParameterSetName)
    {
        "Path" { $list = $Path }
        "LiteralPath" { $list = $LiteralPath }
    }

    # Iterate the items in the list of paths. If an item does not exist,
    # continue to the next item in the list.
    foreach ($item in $list)
    {
        if (-not (test-pathEx $item))
        {
            Write-Error "Unable to find: $item"
            continue
        }

        # Iterate each item in the path. If an item is not a file,
        # skip all remaining items.
        foreach ($file in get-childitemEx $item)
        {
            if ($file -isnot [IO.FileInfo])
            {
                Write-Error "'$file' is not in the file system"
                break
            }

            # Get a temporary file name in the file's directory and create
            # it as a empty file. If set-content fails, continue to the next
            # file. Better to fail before than after reading the file for
            # performance reasons.
            if ($Overwrite)
            {
                $tempname = get-tempname $file.DirectoryName
                Set-Content $tempname $null -Confirm:$false
                if (-not $?) { continue }
                Write-Verbose "Created file: $tempname"
            }

            # Read all the text from the file into a single string. We have
            # to do it this way to be able to search across line breaks.
            try
            {
                Write-Verbose "Reading: $file"
                $text = [IO.File]::ReadAllText($file.FullName)
                Write-Verbose "Finished reading: $file"
            }
            catch [Management.Automation.MethodInvocationException]
            {
                Write-Error $ERROR[0]
                continue
            }

            # If -Overwrite not specified, output the result of the Replace
            # method and continue to the next file.
            if (-not $Overwrite)
            {
                $regex.Replace($text, $Replacement)
                continue
            }

            # Do nothing further if we're in 'what if' mode.
            # if ($WhatIfPreference) { continue }
            if (-not $PSCmdlet.ShouldProcess($Pattern))
            {
                continue
            }

            try
            {
                Write-Verbose "Writing: $tempname"
                [IO.File]::WriteAllText("$tempname", $regex.Replace($text, $Replacement), $encodingObject)
                Write-Verbose "Finished writing: $tempname"
                Write-Verbose "Copying '$tempname' to '$file'"

                Copy-Item $tempname $file -Force:$Force -ErrorAction Continue
                if ($?)
                {
                    Write-Verbose "Finished copying '$tempname' to '$file'"
                }
            }
            catch [Management.Automation.MethodInvocationException]
            {
                Write-Error $ERROR[0]
            }
            finally
            {
                if ((Test-Path -Path $tempname))
                {
                    Remove-Item $tempname -Force
                    Write-Verbose "Removed temp file: $tempname"
                }
            }
        } # foreach $file

    } # foreach $item

} # process

end { }