depreciated/New-psRunspace.ps1

<#
.SYNOPSIS
Start scriptblock in background runspace, which will disposed when finished
 
.DESCRIPTION
Start scriptblock in background runspace, which will disposed when finished
 
.PARAMETER SetVariable
Variables to be parsed in runspace
 
.PARAMETER ScriptBlock
Scriptblock running in runspace
 
.PARAMETER DisposeBlock
Scriptblock for custom actions on dispose
 
.NOTES
added in version 0.0.1
#>

function New-psRunspace ([string[]]$SetVariable, [scriptBlock]$ScriptBlock, [scriptBlock]$DisposeBlock) {
    # Create New Runspace
    #########################################
    $rs = [runspacefactory]::CreateRunspace()
    $rs.ApartmentState = "STA"
    $rs.ThreadOptions = "ReuseThread"
    $rs.Open() | Out-Null

    foreach ($varName in $SetVariable) {
        $v = (Get-Variable -Name $varName).Value

        $rs.SessionStateProxy.SetVariable($varName, $v)
    }

    # Create Powershell Instance
    #########################################
    $ps = [PowerShell]::Create().AddScript($ScriptBlock)
    $ps.Runspace = $rs
    $ps.BeginInvoke() | Out-Null

    # Cleanup Eventhandler
    #########################################
    Register-ObjectEvent -InputObject $rs -EventName 'AvailabilityChanged' -Action {
        if ($Sender.RunspaceAvailability -eq "Available") {

            # Invoke Dispose Block
            #########################################
            if (![string]::IsNullOrEmpty($event.MessageData)) {
                $sb = $event.MessageData
                $sb.invoke()
            }

            $Sender.Closeasync()
            $Sender.Dispose()
        }
    } -MessageData $DisposeBlock | Out-Null

    return $rs
}