Last active
April 13, 2021 18:23
-
-
Save instance-id/1b20852728cc34a70e0ba93527a41c34 to your computer and use it in GitHub Desktop.
Runspace testing. Probably best not to use it yet, though.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.NOTES | |
======================================================= | |
Version: v0.1.00 | |
Created: 04/11/2021 | |
Platform: Linux/Windows | |
PSVersion: 7.2.4 | |
======================================================= | |
.DESCRIPTION | |
Imports modules in separate runspace and returns them to main session | |
#> | |
# ------------------------------------------------------------------------ | |
$moduleArray = @( 'PSWriteHTML', 'PSEverything', 'AWSPowerShell.NetCore' ) | |
# ------------------------------------------------------------------------ | |
$StopWatch = New-Object System.Diagnostics.Stopwatch | |
$StopWatch2 = New-Object System.Diagnostics.Stopwatch | |
$obs = [System.Collections.ObjectModel.ObservableCollection[Object]]::new() | |
$Global:x = [Hashtable]::Synchronized(@{}) | |
$x.Host = $Host | |
$x.ObsCollection = $obs | |
$x.Modules = $moduleArray | |
$x.Imported = $null | |
$rs = [runspacefactory]::CreateRunspace() | |
$rs.ApartmentState, $rs.ThreadOptions = 'STA', 'ReUseThread' | |
$rs.Open() | |
$rs.SessionStateProxy.SetVariable('x', $x) | |
function ImportMods { | |
$Global:x.Imported | Foreach-Object { Import-Module $_ } | |
$StopWatch2.Stop() | |
write-host "Loading Modules To Host Session Complete: $($StopWatch2.ElapsedMilliseconds)ms" -BackgroundColor Black -ForegroundColor Green | |
} | |
$script = { | |
try { | |
$modules = $x.Modules | |
$mods = $modules | Foreach-Object { $mod = Import-Module $_ -PassThru; $mod } | |
$x.Imported = $mods | |
$x.ObsCollection.Add($_) | Out-Null | |
} catch { $x.Host.UI.WriteVerboseLine( $_) } | |
} | |
$psCmd = [PowerShell]::Create().AddScript($script) | |
$psCmd.Runspace = $rs | |
write-host 'Loading Modules' -BackgroundColor Black -ForegroundColor Green | |
$StopWatch.Start() | |
$handle = $psCmd.BeginInvoke() | |
try { | |
$null = Register-ObjectEvent -InputObject $obs -EventName CollectionChanged -Action { | |
$StopWatch.Stop() | |
write-host "Loading Modules Complete $($StopWatch.ElapsedMilliseconds)ms" -BackgroundColor Black -ForegroundColor Green | |
$result = $psCmd.EndInvoke($handle); | |
$StopWatch2.Start() | |
ImportMods | |
$psCmd.Dispose(); $rs.Close(); $rs.Dispose(); Get-EventSubscriber | Unregister-Event | |
} | |
} catch { | |
write-host $_ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment