functions/template-helpers/_executeTemplate.ps1

# <copyright file="_executeTemplate.ps1" company="Endjin Limited">
# Copyright (c) Endjin Limited. All rights reserved.
# </copyright>

function _executeTemplate
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string] $TemplatePath,

        [Parameter(Mandatory=$true)]
        [string] $OutputPath,

        [Parameter()]
        [switch] $Force,

        [Parameter(ValueFromRemainingArguments)]
        [array] $TemplateParameters
    )

    # Convert the format of the 'ValueFromRemainingArguments' parameters into a hashtable
    # format required by EPS' -Binding parameter
    $bindings = @{}
    for ($i=0; $i -lt $TemplateParameters.Count; $i+=2) {
        $bindings.Add($TemplateParameters[$i].TrimStart("-").TrimEnd(":"), $TemplateParameters[$i+1])
    }

    if ( !(Test-Path $OutputPath) -or $Force ) {
        $outputDir = Split-Path -Parent $OutputPath
        # Ensure the containing folders for the output exist
        if (!(Test-Path $outputDir)) {
            New-Item -ItemType Directory -Path $outputDir
        }

        $newFileContent = Invoke-EpsTemplate -Path $TemplatePath -Binding $bindings
        Set-Content -Value $newFileContent -Path $OutputPath -Force:$Force
    }
    else {
        Write-Verbose "The output file '$OutputPath' already exists - specify '-Force' to overwrite"
    }
}