Public/Update-specFileText.ps1

function Update-specFileText {
    <#
    .SYNOPSIS
    Replaces a specified text string in a file with a new string.
 
    .DESCRIPTION
    The Update-specFileText function searches for a given text within a file and replaces it with a specified replacement text.
    If the search text is not found, a warning is displayed and no changes are made.
    The function ensures the file exists before attempting any operations and handles errors gracefully.
 
    .PARAMETER FilePath
    The full path to the file that needs to be modified. This parameter is mandatory.
 
    .PARAMETER SearchText
    The text string to search for within the file. This parameter is mandatory.
 
    .PARAMETER ReplacementText
    The text string that will replace the search text in the file. This parameter is mandatory.
 
    .OUTPUTS
    Boolean
    Returns $true if the replacement was successful, $false if the search text was not found.
 
    .EXAMPLE
    Update-specFileText -FilePath "C:\Temp\example.txt" -SearchText "oldValue" -ReplacementText "newValue"
 
    This example replaces all occurrences of "oldValue" with "newValue" in the file example.txt.
 
    .NOTES
    Author: owen.heaume
    Version: 1.1 - Initial release
    #>



    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$FilePath,

        [Parameter(Mandatory)]
        [string]$SearchText,

        [Parameter(Mandatory)]
        [string]$ReplacementText
    )

    if (!(Test-Path -Path $FilePath)) {
        throw "The file '$FilePath' does not exist."
    }

    try {
        $content = Get-Content -Path $FilePath -Raw -ea Stop

        if ($content -notmatch [regex]::Escape($SearchText)) {
            Write-Warning "Search text '$SearchText' was not found in '$FilePath'. No replacement made."
            return $false
        }

        $updatedContent = $content -replace [regex]::Escape($SearchText), $ReplacementText

        Set-Content -Path $FilePath -Value $updatedContent -Encoding UTF8 -ea Stop

        Write-Verbose "Replaced '$SearchText' with '$ReplacementText' in '$FilePath'."
        return $true
    } catch {
        throw "Failed to update file. Error: $_"
    }
}