Types/OpenPackage.Part/WritePowerShell.ps1

<#
.SYNOPSIS
    Writes Part Content as PowerShell
.DESCRIPTION
    Reads Open Package Part Content as PowerShell
.NOTES
    This may attempt to convert the input into a ScriptBlock.

    It will not write content if the conversion fails.

    If a function is provided as input, will write a script block that declares that function.
#>

[Reflection.AssemblyMetadata(
    # This should automatically apply to `.ps1` and `.psm1` files
    'FilePattern', 
    '\.psm?1$'
)]
param(
# The object to write.
[Alias('Input','Content','Text')]
[PSObject]
$InputObject,

<#

Any options used to write the object

Commonly Supported Options:

|Option|Description|
|-|-|
|Depth|The serialization depth|
|Encoding|The text encoding|
|Stream|Optional destination stream|

#>

[Alias('Options')]
[Collections.IDictionary]
$Option = [Ordered]@{}
)

# If this object does not have a write text method, return.
if (-not $this.WriteText) { throw 'No `.WriteText()`'; return }

# If the input is a scriptblock
if ($inputObject -is [ScriptBlock]) {
    # write it and return.
    $this.WriteText("$InputObject", $Option)
    return
}

# If the input was an external script
if ($inputObject -is [Management.Automation.ExternalScriptInfo]) {
    # write its script block and return
    $this.WriteText("$($InputObject.ScriptBlock)", $Option)
    return
}

# If the input is a function, recreate the function
if ($inputObject -is [Management.Automation.FunctionInfo]) {
    # First check for exotically named commands.
    if ($inputObject.Name -match '[\s\{\}\(\)]') {
        # We can use the function: drive to set them (but only functions).
        if ($inputObject.CommandType -eq 'function') {
            $this.WriteText(@(
                "`$executionContext.SessionState.PSVariable.Set("
                " 'function:$($inputObject.Name -replace "'", "''")',{"
                $InputObject.ScriptBlock
                "})"
            ) -join [Environment]::NewLine)            
        } else {
            Write-Error "Can not recreated $($InputObject.Name) as a filter"
        }
    } else {
        # If the command was not exotically named,
        # we can just embed it directly
        $this.WriteText(@(
            "$($inputObject.CommandType) $($inputObject.Name) {"
            $InputObject.ScriptBlock
            "}"
        ) -join [Environment]::NewLine, $Option)
    }

    return
}

# If the input object was not a ScriptBlock, Function, or ExternalScript
# try to cast the input into a script.
# If this fails, it will output an error
$scriptBlock = [ScriptBlock]::Create("$InputObject")

# If it succeeded, write the text
if ($scriptBlock -is [scriptblock]) {
    $this.WriteText("$scriptBlock", $Option)
}
# Either way, we're done.
return