Functions/New-TextBuilder.ps1

<#
.SYNOPSIS
    This class provides functionality for building up text, with extra functionality for building executable scripts.
#>

class TextBuilder {

    ###########
    # Members #
    ###########
    # This is the current indentation level, in spaces.
    [Int32]$IndentationLevel = 0

    # This holds the current state of the text being built.
    hidden [System.Text.StringBuilder]$_Text = [System.Text.StringBuilder]::new()

    ###########
    # Methods #
    ###########
    # This is the constructor for the text builder.
    TextBuilder() {}

    # This method returns the built text as a single string
    [String]ToString() {
        return $this._Text.ToString()
    }

    # This method adds one or more lines to the text being built, with an additional new line
    # added to the end.
    Add([String]$text) {
        $this.Add($text, "newLine")
    }

    # This method adds one or more lines to the text being built, with the option to choose if
    # an additional new line will be added to the end.
    Add([String]$text, [String]$newLinePolicy) {
        # Split text into lines
        $lines = ConvertTo-Array $text.Split("`n")

        # Add the lines to the text
        foreach ($line in $lines) {
            # The Out-Null is to capture the output from StringBuilder AppendLine
            $this._Text.Append($this.GetIndentationString() + $line + "`n") | Out-Null
        }
        if ($newLinePolicy -eq "newLine") {
            $this._Text.AppendLine("") | Out-Null
        }
    }

    # This method increases the indentation of subsequent lines added to the text by a fixed number of spaces.
    IncreaseIndentation() {
        $this.IncreaseIndentation(4)
    }

    # This method increases the indentation of subsequent lines added to the text by a custom number of spaces.
    IncreaseIndentation([Int32]$numberOfSpaces) {
        $this.IndentationLevel += $numberOfSpaces
    }

    # This method decreases the indentation of subsequent lines added to the text by a fixed number of spaces.
    DecreaseIndentation() {
        $this.DecreaseIndentation(4)
    }

    # This method decreases the indentation of subsequent lines added to the text by a custom number of spaces.
    DecreaseIndentation([Int32]$numberOfSpaces) {
        $this.IndentationLevel -= $numberOfSpaces
    }

    # This method returns a string with the correct number of spaces according to the current indentation level.
    hidden [String]GetIndentationString() {
        return [String]::new(' ', $this.IndentationLevel)
    }
}

<#
.SYNOPSIS
    This function returns a new text builder object.
#>

function New-TextBuilder {
    [CmdletBinding(PositionalBinding=$true)]
    [OutputType([TextBuilder])]
    param ()
    return [TextBuilder]::new()
}