forked from PowerShell/PowerShellEditorServices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPowerShellContext.cs
1944 lines (1679 loc) · 74.4 KB
/
PowerShellContext.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Console;
using Microsoft.PowerShell.EditorServices.Utility;
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.PowerShell.EditorServices
{
using Session;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell.EditorServices.Session.Capabilities;
using System.IO;
/// <summary>
/// Manages the lifetime and usage of a PowerShell session.
/// Handles nested PowerShell prompts and also manages execution of
/// commands whether inside or outside of the debugger.
/// </summary>
public class PowerShellContext : IDisposable, IHostSupportsInteractiveSession
{
#region Fields
private PowerShell powerShell;
private bool ownsInitialRunspace;
private RunspaceDetails initialRunspace;
private SessionDetails mostRecentSessionDetails;
private ProfilePaths profilePaths;
private IVersionSpecificOperations versionSpecificOperations;
private int pipelineThreadId;
private TaskCompletionSource<DebuggerResumeAction> debuggerStoppedTask;
private TaskCompletionSource<IPipelineExecutionRequest> pipelineExecutionTask;
private object runspaceMutex = new object();
private AsyncQueue<RunspaceHandle> runspaceWaitQueue = new AsyncQueue<RunspaceHandle>();
private Stack<RunspaceDetails> runspaceStack = new Stack<RunspaceDetails>();
#endregion
#region Properties
/// <summary>
/// Gets a boolean that indicates whether the debugger is currently stopped,
/// either at a breakpoint or because the user broke execution.
/// </summary>
public bool IsDebuggerStopped
{
get
{
return
this.debuggerStoppedTask != null &&
this.CurrentRunspace.Runspace.RunspaceAvailability != RunspaceAvailability.Available;
}
}
/// <summary>
/// Gets the current state of the session.
/// </summary>
public PowerShellContextState SessionState
{
get;
private set;
}
/// <summary>
/// Gets the PowerShell version details for the initial local runspace.
/// </summary>
public PowerShellVersionDetails LocalPowerShellVersion
{
get;
private set;
}
/// <summary>
/// Gets or sets an IConsoleHost implementation for use in
/// writing output to the console.
/// </summary>
private IConsoleHost ConsoleHost { get; set; }
/// <summary>
/// Gets details pertaining to the current runspace.
/// </summary>
public RunspaceDetails CurrentRunspace
{
get;
private set;
}
#endregion
#region Constructors
/// <summary>
///
/// </summary>
/// <param name="hostDetails"></param>
/// <param name="powerShellContext"></param>
/// <param name="enableConsoleRepl"></param>
/// <returns></returns>
public static Runspace CreateRunspace(
HostDetails hostDetails,
PowerShellContext powerShellContext,
bool enableConsoleRepl)
{
var psHost = new ConsoleServicePSHost(powerShellContext, hostDetails, enableConsoleRepl);
powerShellContext.ConsoleHost = psHost.ConsoleService;
return CreateRunspace(psHost);
}
/// <summary>
///
/// </summary>
/// <param name="psHost"></param>
/// <returns></returns>
public static Runspace CreateRunspace(PSHost psHost)
{
var initialSessionState = InitialSessionState.CreateDefault2();
Runspace runspace = RunspaceFactory.CreateRunspace(psHost, initialSessionState);
#if !CoreCLR
runspace.ApartmentState = ApartmentState.STA;
#endif
runspace.ThreadOptions = PSThreadOptions.ReuseThread;
runspace.Open();
return runspace;
}
/// <summary>
/// Initializes a new instance of the PowerShellContext class using
/// an existing runspace for the session.
/// </summary>
/// <param name="profilePaths">An object containing the profile paths for the session.</param>
/// <param name="initialRunspace">The initial runspace to use for this instance.</param>
/// <param name="ownsInitialRunspace">If true, the PowerShellContext owns this runspace.</param>
public void Initialize(
ProfilePaths profilePaths,
Runspace initialRunspace,
bool ownsInitialRunspace)
{
this.Initialize(profilePaths, initialRunspace, ownsInitialRunspace, null);
}
/// <summary>
/// Initializes a new instance of the PowerShellContext class using
/// an existing runspace for the session.
/// </summary>
/// <param name="profilePaths">An object containing the profile paths for the session.</param>
/// <param name="initialRunspace">The initial runspace to use for this instance.</param>
/// <param name="ownsInitialRunspace">If true, the PowerShellContext owns this runspace.</param>
/// <param name="consoleHost">An IConsoleHost implementation. Optional.</param>
public void Initialize(
ProfilePaths profilePaths,
Runspace initialRunspace,
bool ownsInitialRunspace,
IConsoleHost consoleHost)
{
Validate.IsNotNull("initialRunspace", initialRunspace);
this.ownsInitialRunspace = ownsInitialRunspace;
this.SessionState = PowerShellContextState.NotStarted;
this.ConsoleHost = consoleHost;
// Get the PowerShell runtime version
this.LocalPowerShellVersion =
PowerShellVersionDetails.GetVersionDetails(
initialRunspace);
this.powerShell = PowerShell.Create();
this.powerShell.Runspace = initialRunspace;
this.initialRunspace =
new RunspaceDetails(
initialRunspace,
this.GetSessionDetailsInRunspace(initialRunspace),
this.LocalPowerShellVersion,
RunspaceLocation.Local,
RunspaceContext.Original,
null);
this.CurrentRunspace = this.initialRunspace;
// Write out the PowerShell version for tracking purposes
Logger.Write(
LogLevel.Normal,
string.Format(
"PowerShell runtime version: {0}, edition: {1}",
this.LocalPowerShellVersion.Version,
this.LocalPowerShellVersion.Edition));
Version powerShellVersion = this.LocalPowerShellVersion.Version;
if (powerShellVersion >= new Version(5, 0))
{
this.versionSpecificOperations = new PowerShell5Operations();
}
else if (powerShellVersion.Major == 4)
{
this.versionSpecificOperations = new PowerShell4Operations();
}
else if (powerShellVersion.Major == 3)
{
this.versionSpecificOperations = new PowerShell3Operations();
}
else
{
throw new NotSupportedException(
"This computer has an unsupported version of PowerShell installed: " +
powerShellVersion.ToString());
}
if (this.LocalPowerShellVersion.Edition != "Linux")
{
// TODO: Should this be configurable?
this.SetExecutionPolicy(ExecutionPolicy.RemoteSigned);
}
// Set up the runspace
this.ConfigureRunspace(this.CurrentRunspace);
// Add runspace capabilities
this.ConfigureRunspaceCapabilities(this.CurrentRunspace);
// Set the $profile variable in the runspace
this.profilePaths = profilePaths;
if (this.profilePaths != null)
{
this.SetProfileVariableInCurrentRunspace(profilePaths);
}
// Now that initialization is complete we can watch for InvocationStateChanged
this.powerShell.InvocationStateChanged += powerShell_InvocationStateChanged;
this.SessionState = PowerShellContextState.Ready;
// Now that the runspace is ready, enqueue it for first use
RunspaceHandle runspaceHandle = new RunspaceHandle(this);
this.runspaceWaitQueue.EnqueueAsync(runspaceHandle).Wait();
}
/// <summary>
/// Imports the PowerShellEditorServices.Commands module into
/// the runspace. This method will be moved somewhere else soon.
/// </summary>
/// <param name="moduleBasePath"></param>
/// <returns></returns>
public Task ImportCommandsModule(string moduleBasePath)
{
PSCommand importCommand = new PSCommand();
importCommand
.AddCommand("Import-Module")
.AddArgument(
Path.Combine(
moduleBasePath,
"PowerShellEditorServices.Commands.psd1"));
return this.ExecuteCommand<PSObject>(importCommand, false, false);
}
private static bool CheckIfRunspaceNeedsEventHandlers(RunspaceDetails runspaceDetails)
{
// The only types of runspaces that need to be configured are:
// - Locally created runspaces
// - Local process entered with Enter-PSHostProcess
// - Remote session entered with Enter-PSSession
return
(runspaceDetails.Location == RunspaceLocation.Local &&
(runspaceDetails.Context == RunspaceContext.Original ||
runspaceDetails.Context == RunspaceContext.EnteredProcess)) ||
(runspaceDetails.Location == RunspaceLocation.Remote && runspaceDetails.Context == RunspaceContext.Original);
}
private void ConfigureRunspace(RunspaceDetails runspaceDetails)
{
runspaceDetails.Runspace.StateChanged += this.HandleRunspaceStateChanged;
if (runspaceDetails.Runspace.Debugger != null)
{
runspaceDetails.Runspace.Debugger.BreakpointUpdated += OnBreakpointUpdated;
runspaceDetails.Runspace.Debugger.DebuggerStop += OnDebuggerStop;
}
this.versionSpecificOperations.ConfigureDebugger(runspaceDetails.Runspace);
}
private void CleanupRunspace(RunspaceDetails runspaceDetails)
{
runspaceDetails.Runspace.StateChanged -= this.HandleRunspaceStateChanged;
if (runspaceDetails.Runspace.Debugger != null)
{
runspaceDetails.Runspace.Debugger.BreakpointUpdated -= OnBreakpointUpdated;
runspaceDetails.Runspace.Debugger.DebuggerStop -= OnDebuggerStop;
}
}
#endregion
#region Public Methods
/// <summary>
/// Gets a RunspaceHandle for the session's runspace. This
/// handle is used to gain temporary ownership of the runspace
/// so that commands can be executed against it directly.
/// </summary>
/// <returns>A RunspaceHandle instance that gives access to the session's runspace.</returns>
public Task<RunspaceHandle> GetRunspaceHandle()
{
return this.GetRunspaceHandle(CancellationToken.None);
}
/// <summary>
/// Gets a RunspaceHandle for the session's runspace. This
/// handle is used to gain temporary ownership of the runspace
/// so that commands can be executed against it directly.
/// </summary>
/// <param name="cancellationToken">A CancellationToken that can be used to cancel the request.</param>
/// <returns>A RunspaceHandle instance that gives access to the session's runspace.</returns>
public Task<RunspaceHandle> GetRunspaceHandle(CancellationToken cancellationToken)
{
return this.runspaceWaitQueue.DequeueAsync(cancellationToken);
}
/// <summary>
/// Executes a PSCommand against the session's runspace and returns
/// a collection of results of the expected type.
/// </summary>
/// <typeparam name="TResult">The expected result type.</typeparam>
/// <param name="psCommand">The PSCommand to be executed.</param>
/// <param name="sendOutputToHost">
/// If true, causes any output written during command execution to be written to the host.
/// </param>
/// <param name="sendErrorToHost">
/// If true, causes any errors encountered during command execution to be written to the host.
/// </param>
/// <returns>
/// An awaitable Task which will provide results once the command
/// execution completes.
/// </returns>
public async Task<IEnumerable<TResult>> ExecuteCommand<TResult>(
PSCommand psCommand,
bool sendOutputToHost = false,
bool sendErrorToHost = true)
{
return await ExecuteCommand<TResult>(psCommand, null, sendOutputToHost, sendErrorToHost);
}
/// <summary>
/// Executes a PSCommand against the session's runspace and returns
/// a collection of results of the expected type.
/// </summary>
/// <typeparam name="TResult">The expected result type.</typeparam>
/// <param name="psCommand">The PSCommand to be executed.</param>
/// <param name="errorMessages">Error messages from PowerShell will be written to the StringBuilder.</param>
/// <param name="sendOutputToHost">
/// If true, causes any output written during command execution to be written to the host.
/// </param>
/// <param name="sendErrorToHost">
/// If true, causes any errors encountered during command execution to be written to the host.
/// </param>
/// <param name="addToHistory">
/// If true, adds the command to the user's command history.
/// </param>
/// <returns>
/// An awaitable Task which will provide results once the command
/// execution completes.
/// </returns>
public Task<IEnumerable<TResult>> ExecuteCommand<TResult>(
PSCommand psCommand,
StringBuilder errorMessages,
bool sendOutputToHost = false,
bool sendErrorToHost = true,
bool addToHistory = false)
{
return
this.ExecuteCommand<TResult>(
psCommand,
errorMessages,
new ExecutionOptions
{
WriteOutputToHost = sendOutputToHost,
WriteErrorsToHost = sendErrorToHost,
AddToHistory = addToHistory
});
}
/// <summary>
/// Executes a PSCommand against the session's runspace and returns
/// a collection of results of the expected type.
/// </summary>
/// <typeparam name="TResult">The expected result type.</typeparam>
/// <param name="psCommand">The PSCommand to be executed.</param>
/// <param name="errorMessages">Error messages from PowerShell will be written to the StringBuilder.</param>
/// <param name="executionOptions">Specifies options to be used when executing this command.</param>
/// <returns>
/// An awaitable Task which will provide results once the command
/// execution completes.
/// </returns>
public async Task<IEnumerable<TResult>> ExecuteCommand<TResult>(
PSCommand psCommand,
StringBuilder errorMessages,
ExecutionOptions executionOptions)
{
bool hadErrors = false;
RunspaceHandle runspaceHandle = null;
IEnumerable<TResult> executionResult = Enumerable.Empty<TResult>();
// If the debugger is active and the caller isn't on the pipeline
// thread, send the command over to that thread to be executed.
if (Thread.CurrentThread.ManagedThreadId != this.pipelineThreadId &&
this.pipelineExecutionTask != null)
{
Logger.Write(LogLevel.Verbose, "Passing command execution to pipeline thread.");
PipelineExecutionRequest<TResult> executionRequest =
new PipelineExecutionRequest<TResult>(
this,
psCommand,
errorMessages,
executionOptions.WriteOutputToHost);
// Send the pipeline execution request to the pipeline thread
this.pipelineExecutionTask.SetResult(executionRequest);
return await executionRequest.Results;
}
else
{
try
{
// Instruct PowerShell to send output and errors to the host
if (executionOptions.WriteOutputToHost)
{
psCommand.Commands[0].MergeMyResults(
PipelineResultTypes.Error,
PipelineResultTypes.Output);
psCommand.Commands.Add(
this.GetOutputCommand(
endOfStatement: false));
}
this.OnExecutionStatusChanged(
ExecutionStatus.Running,
executionOptions,
false);
if (this.CurrentRunspace.Runspace.RunspaceAvailability == RunspaceAvailability.AvailableForNestedCommand ||
this.debuggerStoppedTask != null)
{
executionResult =
this.ExecuteCommandInDebugger<TResult>(
psCommand,
executionOptions.WriteOutputToHost);
}
else
{
Logger.Write(
LogLevel.Verbose,
string.Format(
"Attempting to execute command(s):\r\n\r\n{0}",
GetStringForPSCommand(psCommand)));
// Set the runspace
runspaceHandle = await this.GetRunspaceHandle();
if (runspaceHandle.Runspace.RunspaceAvailability != RunspaceAvailability.AvailableForNestedCommand)
{
this.powerShell.Runspace = runspaceHandle.Runspace;
}
// Invoke the pipeline on a background thread
// TODO: Use built-in async invocation!
executionResult =
await Task.Factory.StartNew<IEnumerable<TResult>>(
() =>
{
Collection<TResult> result = null;
try
{
this.powerShell.Commands = psCommand;
PSInvocationSettings invocationSettings = new PSInvocationSettings();
invocationSettings.AddToHistory = executionOptions.AddToHistory;
result = this.powerShell.Invoke<TResult>(null, invocationSettings);
}
catch (RemoteException e)
{
if (!e.SerializedRemoteException.TypeNames[0].EndsWith("PipelineStoppedException"))
{
// Rethrow anything that isn't a PipelineStoppedException
throw e;
}
}
return result;
},
CancellationToken.None, // Might need a cancellation token
TaskCreationOptions.None,
TaskScheduler.Default
);
if (this.powerShell.HadErrors)
{
string errorMessage = "Execution completed with errors:\r\n\r\n";
foreach (var error in this.powerShell.Streams.Error)
{
errorMessage += error.ToString() + "\r\n";
}
errorMessages?.Append(errorMessage);
Logger.Write(LogLevel.Error, errorMessage);
hadErrors = true;
}
else
{
Logger.Write(
LogLevel.Verbose,
"Execution completed successfully.");
}
}
}
catch (PipelineStoppedException e)
{
Logger.Write(
LogLevel.Error,
"Pipeline stopped while executing command:\r\n\r\n" + e.ToString());
errorMessages?.Append(e.Message);
}
catch (RuntimeException e)
{
Logger.Write(
LogLevel.Error,
"Runtime exception occurred while executing command:\r\n\r\n" + e.ToString());
hadErrors = true;
errorMessages?.Append(e.Message);
if (executionOptions.WriteErrorsToHost)
{
// Write the error to the host
this.WriteExceptionToHost(e);
}
}
catch (Exception e)
{
this.OnExecutionStatusChanged(
ExecutionStatus.Failed,
executionOptions,
true);
throw e;
}
finally
{
// Get the new prompt before releasing the runspace handle
if (executionOptions.WriteOutputToHost)
{
SessionDetails sessionDetails = null;
// Get the SessionDetails and then write the prompt
if (this.CurrentRunspace.Runspace.RunspaceAvailability == RunspaceAvailability.Available)
{
// This state can happen if the user types a command that causes the
// debugger to exit before we reach this point. No RunspaceHandle
// will exist already so we need to create one and then use it
if (runspaceHandle == null)
{
runspaceHandle = await this.GetRunspaceHandle();
}
sessionDetails = this.GetSessionDetailsInRunspace(runspaceHandle.Runspace);
}
else if (this.IsDebuggerStopped)
{
sessionDetails = this.GetSessionDetailsInDebugger();
}
else
{
sessionDetails = this.GetSessionDetailsInNestedPipeline();
}
// Check if the runspace has changed
this.UpdateRunspaceDetailsIfSessionChanged(sessionDetails);
}
// Dispose of the execution context
if (runspaceHandle != null)
{
runspaceHandle.Dispose();
}
}
}
this.OnExecutionStatusChanged(
ExecutionStatus.Completed,
executionOptions,
hadErrors);
return executionResult;
}
/// <summary>
/// Executes a PSCommand in the session's runspace without
/// expecting to receive any result.
/// </summary>
/// <param name="psCommand">The PSCommand to be executed.</param>
/// <returns>
/// An awaitable Task that the caller can use to know when
/// execution completes.
/// </returns>
public Task ExecuteCommand(PSCommand psCommand)
{
return this.ExecuteCommand<object>(psCommand);
}
/// <summary>
/// Executes a script string in the session's runspace.
/// </summary>
/// <param name="scriptString">The script string to execute.</param>
/// <returns>A Task that can be awaited for the script completion.</returns>
public Task<IEnumerable<object>> ExecuteScriptString(
string scriptString)
{
return this.ExecuteScriptString(scriptString, false, true);
}
/// <summary>
/// Executes a script string in the session's runspace.
/// </summary>
/// <param name="scriptString">The script string to execute.</param>
/// <param name="errorMessages">Error messages from PowerShell will be written to the StringBuilder.</param>
/// <returns>A Task that can be awaited for the script completion.</returns>
public Task<IEnumerable<object>> ExecuteScriptString(
string scriptString,
StringBuilder errorMessages)
{
return this.ExecuteScriptString(scriptString, errorMessages, false, true, false);
}
/// <summary>
/// Executes a script string in the session's runspace.
/// </summary>
/// <param name="scriptString">The script string to execute.</param>
/// <param name="writeInputToHost">If true, causes the script string to be written to the host.</param>
/// <param name="writeOutputToHost">If true, causes the script output to be written to the host.</param>
/// <returns>A Task that can be awaited for the script completion.</returns>
public Task<IEnumerable<object>> ExecuteScriptString(
string scriptString,
bool writeInputToHost,
bool writeOutputToHost)
{
return this.ExecuteScriptString(scriptString, null, writeInputToHost, writeOutputToHost, false);
}
/// <summary>
/// Executes a script string in the session's runspace.
/// </summary>
/// <param name="scriptString">The script string to execute.</param>
/// <param name="writeInputToHost">If true, causes the script string to be written to the host.</param>
/// <param name="writeOutputToHost">If true, causes the script output to be written to the host.</param>
/// <param name="addToHistory">If true, adds the command to the user's command history.</param>
/// <returns>A Task that can be awaited for the script completion.</returns>
public Task<IEnumerable<object>> ExecuteScriptString(
string scriptString,
bool writeInputToHost,
bool writeOutputToHost,
bool addToHistory)
{
return this.ExecuteScriptString(scriptString, null, writeInputToHost, writeOutputToHost, addToHistory);
}
/// <summary>
/// Executes a script string in the session's runspace.
/// </summary>
/// <param name="scriptString">The script string to execute.</param>
/// <param name="errorMessages">Error messages from PowerShell will be written to the StringBuilder.</param>
/// <param name="writeInputToHost">If true, causes the script string to be written to the host.</param>
/// <param name="writeOutputToHost">If true, causes the script output to be written to the host.</param>
/// <param name="addToHistory">If true, adds the command to the user's command history.</param>
/// <returns>A Task that can be awaited for the script completion.</returns>
public async Task<IEnumerable<object>> ExecuteScriptString(
string scriptString,
StringBuilder errorMessages,
bool writeInputToHost,
bool writeOutputToHost,
bool addToHistory)
{
if (writeInputToHost)
{
this.WriteOutput(
scriptString + Environment.NewLine,
true);
}
PSCommand psCommand = new PSCommand();
psCommand.AddScript(scriptString);
return
await this.ExecuteCommand<object>(
psCommand,
errorMessages,
writeOutputToHost,
addToHistory: addToHistory);
}
/// <summary>
/// Executes a script file at the specified path.
/// </summary>
/// <param name="script">The script execute.</param>
/// <param name="arguments">Arguments to pass to the script.</param>
/// <param name="writeInputToHost">Writes the executed script path and arguments to the host.</param>
/// <returns>A Task that can be awaited for completion.</returns>
public async Task ExecuteScriptWithArgs(string script, string arguments = null, bool writeInputToHost = false)
{
string launchedScript = script;
PSCommand command = new PSCommand();
if (arguments != null)
{
// Need to determine If the script string is a path to a script file.
string scriptAbsPath = string.Empty;
try
{
// Assume we can only debug scripts from the FileSystem provider
string workingDir =
this.CurrentRunspace.Runspace.SessionStateProxy.Path.CurrentFileSystemLocation.ProviderPath;
workingDir = workingDir.TrimEnd(Path.DirectorySeparatorChar);
scriptAbsPath = workingDir + Path.DirectorySeparatorChar + script;
}
catch (System.Management.Automation.DriveNotFoundException e)
{
Logger.Write(
LogLevel.Error,
"Could not determine current filesystem location:\r\n\r\n" + e.ToString());
}
// If we don't escape wildcard characters in a path to a script file, the script can
// fail to execute if say the script filename was foo][.ps1.
// Related to issue #123.
if (File.Exists(script) || File.Exists(scriptAbsPath))
{
// Dot-source the launched script path
script = ". " + EscapePath(script, escapeSpaces: true);
}
launchedScript = script + " " + arguments;
command.AddScript(launchedScript, false);
}
else
{
command.AddCommand(script, false);
}
if (writeInputToHost)
{
this.WriteOutput(
launchedScript + Environment.NewLine,
true);
}
await this.ExecuteCommand<object>(
command,
null,
sendOutputToHost: true,
addToHistory: true);
}
internal static TResult ExecuteScriptAndGetItem<TResult>(string scriptToExecute, Runspace runspace, TResult defaultValue = default(TResult))
{
Pipeline pipeline = null;
try
{
if (runspace.RunspaceAvailability == RunspaceAvailability.AvailableForNestedCommand)
{
pipeline = runspace.CreateNestedPipeline(scriptToExecute, false);
}
else
{
pipeline = runspace.CreatePipeline(scriptToExecute, false);
}
Collection<PSObject> results = pipeline.Invoke();
if (results.Count == 0)
{
return defaultValue;
}
if (typeof(TResult) != typeof(PSObject))
{
return
results
.Select(pso => pso.BaseObject)
.OfType<TResult>()
.FirstOrDefault();
}
else
{
return
results
.OfType<TResult>()
.FirstOrDefault();
}
}
finally
{
pipeline.Dispose();
}
}
/// <summary>
/// Loads PowerShell profiles for the host from the specified
/// profile locations. Only the profile paths which exist are
/// loaded.
/// </summary>
/// <returns>A Task that can be awaited for completion.</returns>
public async Task LoadHostProfiles()
{
if (this.profilePaths != null)
{
// Load any of the profile paths that exist
PSCommand command = null;
foreach (var profilePath in this.profilePaths.GetLoadableProfilePaths())
{
command = new PSCommand();
command.AddCommand(profilePath, false);
await this.ExecuteCommand<object>(command, true, true);
}
// Gather the session details (particularly the prompt) after
// loading the user's profiles.
await this.GetSessionDetailsInRunspace();
}
}
/// <summary>
/// Causes the current execution to be aborted no matter what state
/// it is currently in.
/// </summary>
public void AbortExecution()
{
if (this.SessionState != PowerShellContextState.Aborting &&
this.SessionState != PowerShellContextState.Disposed)
{
Logger.Write(LogLevel.Verbose, "Execution abort requested...");
// Clean up the debugger
if (this.IsDebuggerStopped)
{
this.ResumeDebugger(DebuggerResumeAction.Stop);
this.debuggerStoppedTask = null;
this.pipelineExecutionTask = null;
}
// Stop the running pipeline
this.powerShell.BeginStop(null, null);
this.SessionState = PowerShellContextState.Aborting;
this.OnExecutionStatusChanged(
ExecutionStatus.Aborted,
null,
false);
}
else
{
Logger.Write(
LogLevel.Verbose,
string.Format(
$"Execution abort requested when already aborted (SessionState = {this.SessionState})"));
}
}
/// <summary>
/// Causes the debugger to break execution wherever it currently is.
/// This method is internal because the real Break API is provided
/// by the DebugService.
/// </summary>
internal void BreakExecution()
{
Logger.Write(LogLevel.Verbose, "Debugger break requested...");
// Pause the debugger
this.versionSpecificOperations.PauseDebugger(
this.CurrentRunspace.Runspace);
}
internal void ResumeDebugger(DebuggerResumeAction resumeAction)
{
if (this.debuggerStoppedTask != null)
{
// Set the result so that the execution thread resumes.
// The execution thread will clean up the task.
if (!this.debuggerStoppedTask.TrySetResult(resumeAction))
{
Logger.Write(
LogLevel.Error,
$"Tried to resume debugger with action {resumeAction} but the task was already completed.");
}
}
else
{
Logger.Write(
LogLevel.Error,
$"Tried to resume debugger with action {resumeAction} but there was no debuggerStoppedTask.");
}
}
/// <summary>
/// Disposes the runspace and any other resources being used
/// by this PowerShellContext.
/// </summary>
public void Dispose()
{
// Do we need to abort a running execution?
if (this.SessionState == PowerShellContextState.Running ||
this.IsDebuggerStopped)
{
this.AbortExecution();
}
this.SessionState = PowerShellContextState.Disposed;
if (this.powerShell != null)
{
this.powerShell.InvocationStateChanged -= this.powerShell_InvocationStateChanged;
this.powerShell.Dispose();
this.powerShell = null;
}
// Clean up the active runspace
this.CleanupRunspace(this.CurrentRunspace);
// Push the active runspace so it will be included in the loop
this.runspaceStack.Push(this.CurrentRunspace);
while (this.runspaceStack.Count > 0)
{
RunspaceDetails poppedRunspace = this.runspaceStack.Pop();
// Close the popped runspace if it isn't the initial runspace
// or if it is the initial runspace and we own that runspace
if (this.initialRunspace != poppedRunspace || this.ownsInitialRunspace)
{
this.CloseRunspace(poppedRunspace);
}
this.OnRunspaceChanged(
this,
new RunspaceChangedEventArgs(
RunspaceChangeAction.Shutdown,
poppedRunspace,
null));
}
this.initialRunspace = null;
}
private void CloseRunspace(RunspaceDetails runspaceDetails)
{
string exitCommand = null;
switch (runspaceDetails.Context)
{
case RunspaceContext.Original:
if (runspaceDetails.Location == RunspaceLocation.Local)
{
runspaceDetails.Runspace.Close();
runspaceDetails.Runspace.Dispose();
}
else
{
exitCommand = "Exit-PSSession";
}
break;
case RunspaceContext.EnteredProcess:
exitCommand = "Exit-PSHostProcess";
break;
case RunspaceContext.DebuggedRunspace:
// An attached runspace will be detached when the
// running pipeline is aborted