Functions/Invoke-ScriptBlock.ps1

<#
.SYNOPSIS
    This function invokes a script block, catching an exception and generating an error if it occurs, and verifies the result.
.DESCRIPTION
    This function invokes a script block, catching an exception and generating an error if it occurs, and verifies the result.
    The result verification is only performed if an expected result is provided.
#>

function Invoke-ScriptBlock {
    [CmdletBinding(PositionalBinding=$true)]
    param (
        # The description of what the script block is accomplishing.
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$description,

        # The script block to execute
        [Parameter(Mandatory=$true)]
        [ValidateNotNull()]
        [ScriptBlock]$scriptBlock,

        # Indicates if the script block should have output.
        [Parameter(Mandatory=$false)]
        [Switch]$shouldHaveOutput,

        # The expected output from the script block.
        [Parameter(Mandatory=$false)]
        [ValidateNotNull()]
        $expectedOutput
    )

    # Invoke the script block
    try {
        $output = & $scriptBlock
        $errorMessage = $null
    }

    # Exception while invoking the script block
    catch {
        $errorMessage = "Exception during '$($description)'.`r`n$($_.Exception.Message)"
        Write-Error $errorMessage
    }

    # Verify the output if no exception was thrown
    if ([String]::IsNullOrWhiteSpace($errorMessage)) {
        # Output is expected but not specified
        if ($shouldHaveOutput) {
            if (!$output) {
                $errorMessage = "Failed to '$($description)' - no output when an output is expected."
                Write-Error $errorMessage
            }
        }

        # Expected output is specified
        elseif ($expectedOutput) {
            if ($output -cne $expectedOutput) {
                $errorMessage = "Failed to '$($description)' - the output does not match the expected output."
                Write-Error $errorMessage
            }
        }
    }

    # Return the result of invoking the script block as well as the error message (if any)
    return [PSCustomObject]@{
        PSTypeName      = "Invoke-TryCatchVerify.Output"
        Output          = $output
        ErrorMessage    = $errorMessage
    }
}