Skip to content

Created a nested PowerShell for the top-level loop #1918

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 13, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -475,8 +475,18 @@ private void Run()
(PowerShell pwsh, RunspaceInfo localRunspaceInfo, EngineIntrinsics engineIntrinsics) = CreateInitialPowerShellSession();
_mainRunspaceEngineIntrinsics = engineIntrinsics;
_localComputerName = localRunspaceInfo.SessionDetails.ComputerName;
_runspaceStack.Push(new RunspaceFrame(pwsh.Runspace, localRunspaceInfo));
PushPowerShellAndRunLoop(pwsh, PowerShellFrameType.Normal | PowerShellFrameType.Repl, localRunspaceInfo);

// NOTE: In order to support running events registered to PowerShell's OnIdle
// handler, we have to have our top-level PowerShell instance be nested (otherwise
// we get a PSInvalidOperationException because pipelines cannot be run
// concurrently). Specifically this bug cropped up when a profile loaded code which
// registered (and subsequently ran) on the OnIdle handler since it was hitting the
// non-nested PowerShell instance. So now we just start with a nested instance.
// While the PowerShell object is nested, as a frame type, this is our top-level
// frame and therefore NOT nested in that sense.
PowerShell nestedPwsh = CreateNestedPowerShell(localRunspaceInfo);
_runspaceStack.Push(new RunspaceFrame(nestedPwsh.Runspace, localRunspaceInfo));
PushPowerShellAndRunLoop(nestedPwsh, PowerShellFrameType.Normal | PowerShellFrameType.Repl, localRunspaceInfo);
}
catch (Exception e)
{
Expand Down Expand Up @@ -964,9 +974,7 @@ private static PowerShell CreateNestedPowerShell(RunspaceInfo currentRunspace)
// PowerShell.CreateNestedPowerShell() sets IsNested but not IsChild
// This means it throws due to the parent pipeline not running...
// So we must use the RunspaceMode.CurrentRunspace option on PowerShell.Create() instead
PowerShell pwsh = PowerShell.Create(RunspaceMode.CurrentRunspace);
pwsh.Runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
return pwsh;
return PowerShell.Create(RunspaceMode.CurrentRunspace);
}

private static PowerShell CreatePowerShellForRunspace(Runspace runspace)
Expand Down