Public/Update-specFileLine.ps1

function Update-specFileLine {
    <#
    .SYNOPSIS
        Updates a specific line in a file based on a search pattern.
 
    .DESCRIPTION
        This function is designed to search for a specific line in a file using a provided search pattern,
        and if a match is found, it replaces the line with the specified replacement line.
 
    .PARAMETER FilePath
        Specifies the path to the file that needs to be updated.
 
    .PARAMETER SearchPattern
        Specifies the pattern to search for in each line of the file. The comparison is based on the start of the line. (startswith)
 
    .PARAMETER ReplacementLine
        Specifies the line that will replace the matching line if found.
 
    .EXAMPLE
        Update-SpecFileLine -FilePath "C:\Path\To\File.txt" -SearchPattern "GiftCard.url=" -ReplacementLine "GiftCard.url=http://my.newurl.com"
 
        This example updates the line in the file "File.txt" where the line starts with "GiftCard.url=".
        If a match is found, the line is replaced with "GiftCard.url=http://my.newurl.com".
 
    .NOTES
        Author: owen.heaume
        Version: 1.0.0 - Initial release
    #>


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

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

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

    # Check if the file exists
    if (-not (Test-Path $FilePath)) {
        Write-Host "File not found: $FilePath" -ForegroundColor darkyellow
        return
    }

    # Read the contents of the file
    $content = Get-Content $FilePath

    # Find and replace lines (if a match is found and content is different)
    $updatedContent = $false
    for ($i = 0; $i -lt $content.Count; $i++) {
        # Future Owen... '^' is regex for 'starts with'. Could just have easily used: if ($content[$i].startswith($SearchPattern)... - practicing my regex!
        if ($content[$i] -match "^$SearchPattern" -and $content[$i] -ne $ReplacementLine) {
            $content[$i] = $ReplacementLine
            $updatedContent = $true
            break
        }
    }

    # Write updated content if changes were made
    if ($updatedContent) {
        Set-Content $FilePath $content
        Write-Host "Line updated in $FilePath" -ForegroundColor darkgreen
    } else {
        Write-Host "Matching line not found or content already up-to-date in $FilePath" -ForegroundColor DarkYellow
    }
}