Skip to main content

Replaces text in a string based on named replacement tags.

function Format-String
{
    <#
    .SYNOPSIS
        Replaces text in a string based on named replacement tags.

    .EXAMPLE
        PS > Format-String "Hello {NAME}" @{ NAME = 'PowerShell' }
        Hello PowerShell

    .EXAMPLE
        PS > Format-String "Your score is {SCORE:P}" @{ SCORE = 0.85 }
        Your score is 85.00%

    .EXAMPLE
        PS > Format-String "Today's date is {TODAY:D}" @{ TODAY = (Get-Date) }
        Today's date is Tuesday, September 6, 2022
    #>
    param(
        # The string to format. Any portions in the form of {NAME} will be automatically replaced by the corresponding value from the supplied hashtable.
        [String]
        $String,

        # The named replacements to use in the string.
        [Hashtable]
        $Replacements
    )

    $currentIndex = 0
    $replacementList = @()

    if ($String -match '{{|}}')
    {
        throw 'Escaping replacement terms is not supported.'
    }

    ## Go through each key in the hashtable
    foreach ($key in $replacements.Keys)
    {
        # Convert the key into a number, so that it can be used by String.Format
        $inputPattern = '{(.*)' + $key + '(.*)}'
        $replacementPattern = '{${1}' + $currentIndex + '${2}}'
        $string = $string -replace $inputPattern, $replacementPattern
        $replacementList += $replacements[$key]
        $currentIndex++
    }

    # Now use String.Format to replace the numbers in the format string.
    $string -f $replacementList
}