|
1 |
| -// Copyright (c) Microsoft Corporation. |
| 1 | +// Copyright (c) Microsoft Corporation. |
2 | 2 | // Licensed under the MIT License.
|
3 | 3 |
|
4 | 4 | using System;
|
@@ -502,15 +502,27 @@ private void PopPowerShell(RunspaceChangeAction runspaceChangeAction = RunspaceC
|
502 | 502 | PowerShellContextFrame frame = _psFrameStack.Pop();
|
503 | 503 | try
|
504 | 504 | {
|
505 |
| - // If we're changing runspace, make sure we move the handlers over |
506 |
| - RunspaceFrame previousRunspaceFrame = _runspaceStack.Peek(); |
507 |
| - if (previousRunspaceFrame.Runspace != CurrentPowerShell.Runspace) |
| 505 | + // If we're changing runspace, make sure we move the handlers over. If we just |
| 506 | + // popped the last frame, then we're exiting and should pop the runspace too. |
| 507 | + if (_psFrameStack.Count == 0 |
| 508 | + || _runspaceStack.Peek().Runspace != _psFrameStack.Peek().PowerShell.Runspace) |
508 | 509 | {
|
509 |
| - _runspaceStack.Pop(); |
510 |
| - RunspaceFrame currentRunspaceFrame = _runspaceStack.Peek(); |
| 510 | + RunspaceFrame previousRunspaceFrame = _runspaceStack.Pop(); |
511 | 511 | RemoveRunspaceEventHandlers(previousRunspaceFrame.Runspace);
|
512 |
| - AddRunspaceEventHandlers(currentRunspaceFrame.Runspace); |
513 |
| - RunspaceChanged?.Invoke(this, new RunspaceChangedEventArgs(runspaceChangeAction, previousRunspaceFrame.RunspaceInfo, currentRunspaceFrame.RunspaceInfo)); |
| 512 | + |
| 513 | + // If there is still a runspace on the stack, then we need to re-register the |
| 514 | + // handlers. Otherwise we're exiting and so don't need to run 'RunspaceChanged'. |
| 515 | + if (_runspaceStack.Count > 0) |
| 516 | + { |
| 517 | + RunspaceFrame newRunspaceFrame = _runspaceStack.Peek(); |
| 518 | + AddRunspaceEventHandlers(newRunspaceFrame.Runspace); |
| 519 | + RunspaceChanged?.Invoke( |
| 520 | + this, |
| 521 | + new RunspaceChangedEventArgs( |
| 522 | + runspaceChangeAction, |
| 523 | + previousRunspaceFrame.RunspaceInfo, |
| 524 | + newRunspaceFrame.RunspaceInfo)); |
| 525 | + } |
514 | 526 | }
|
515 | 527 | }
|
516 | 528 | finally
|
|
0 commit comments