@@ -475,8 +475,18 @@ private void Run()
475
475
( PowerShell pwsh , RunspaceInfo localRunspaceInfo , EngineIntrinsics engineIntrinsics ) = CreateInitialPowerShellSession ( ) ;
476
476
_mainRunspaceEngineIntrinsics = engineIntrinsics ;
477
477
_localComputerName = localRunspaceInfo . SessionDetails . ComputerName ;
478
- _runspaceStack . Push ( new RunspaceFrame ( pwsh . Runspace , localRunspaceInfo ) ) ;
479
- PushPowerShellAndRunLoop ( pwsh , PowerShellFrameType . Normal | PowerShellFrameType . Repl , localRunspaceInfo ) ;
478
+
479
+ // NOTE: In order to support running events registered to PowerShell's OnIdle
480
+ // handler, we have to have our top-level PowerShell instance be nested (otherwise
481
+ // we get a PSInvalidOperationException because pipelines cannot be run
482
+ // concurrently). Specifically this bug cropped up when a profile loaded code which
483
+ // registered (and subsequently ran) on the OnIdle handler since it was hitting the
484
+ // non-nested PowerShell instance. So now we just start with a nested instance.
485
+ // While the PowerShell object is nested, as a frame type, this is our top-level
486
+ // frame and therefore NOT nested in that sense.
487
+ PowerShell nestedPwsh = CreateNestedPowerShell ( localRunspaceInfo ) ;
488
+ _runspaceStack . Push ( new RunspaceFrame ( nestedPwsh . Runspace , localRunspaceInfo ) ) ;
489
+ PushPowerShellAndRunLoop ( nestedPwsh , PowerShellFrameType . Normal | PowerShellFrameType . Repl , localRunspaceInfo ) ;
480
490
}
481
491
catch ( Exception e )
482
492
{
@@ -964,9 +974,7 @@ private static PowerShell CreateNestedPowerShell(RunspaceInfo currentRunspace)
964
974
// PowerShell.CreateNestedPowerShell() sets IsNested but not IsChild
965
975
// This means it throws due to the parent pipeline not running...
966
976
// So we must use the RunspaceMode.CurrentRunspace option on PowerShell.Create() instead
967
- PowerShell pwsh = PowerShell . Create ( RunspaceMode . CurrentRunspace ) ;
968
- pwsh . Runspace . ThreadOptions = PSThreadOptions . UseCurrentThread ;
969
- return pwsh ;
977
+ return PowerShell . Create ( RunspaceMode . CurrentRunspace ) ;
970
978
}
971
979
972
980
private static PowerShell CreatePowerShellForRunspace ( Runspace runspace )
0 commit comments