Deep dive into PowerShell runspaces.
In this video, I go through a primer on runspaces. I got through creating runspaces and running scripts synchronously and asynchronously. I also initialize a runspace with a variable, create an out of process runspace and connect to another PowerShell process using named pipes.
The code for this video can be found below.
Get-Runspace
$Runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace() $Runspace.Open() Get-Runspace $Runspace.Dispose()
$Runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace() $Runspace.Open() $PowerShell = [PowerShell]::Create() $PowerShell.Runspace = $Runspace $PowerShell.AddScript("Set-Variable -Name 'Test' -Value 123"); $PowerShell.Invoke() $Test $PowerShell.Dispose() $PowerShell = [PowerShell]::Create() $PowerShell.Runspace = $Runspace $PowerShell.AddScript("Get-Variable -Name 'Test' -ValueOnly"); $PowerShell.Invoke()
$Runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace() $Runspace.Open() $PowerShell = [PowerShell]::Create() $PowerShell.Runspace = $Runspace $PowerShell.AddScript("1..10 | ForEach-Object { Start-Sleep 1 }; 'Hello, from another runspace!!' "); $Result = $PowerShell.InvokeAsync() $Result.IsCompleted $Result.Result
$init = [System.Management.Automation.Runspaces.InitialSessionState]::Create() $init | Get-Member $variable = [System.Management.Automation.Runspaces.SessionStateVariableEntry]::new("Test", 123, '') $init.LanguageMode = 'FullLanguage' $init.Variables.Add($variable) $Runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($init) $Runspace.Open() $PowerShell = [PowerShell]::Create() $PowerShell.Runspace = $Runspace $PowerShell.AddScript("`$Test"); $PowerShell.Invoke();
$PID $TypeTable = [System.Management.Automation.Runspaces.TypeTable]::LoadDefaultTypeFiles() $Runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateOutOfProcessRunspace($TypeTable) $Runspace.Open() $PowerShell = [PowerShell]::Create() $PowerShell.Runspace = $Runspace $PowerShell.AddScript("`$PID"); $PowerShell.Invoke();
$CI = [System.Management.Automation.Runspaces.NamedPipeConnectionInfo]::new($ProcessId) $Runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($CI) $Runspace.Open() $PowerShell = [PowerShell]::Create() $PowerShell.Runspace = $Runspace $PowerShell.AddScript("`$PID"); $PowerShell.Invoke(); Get-Runspace
Start-ThreadJob { Start-Sleep 20 } Get-Runspace