/
MshCommandRuntime.cs
3807 lines (3409 loc) · 155 KB
/
MshCommandRuntime.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 Corporation.
// Licensed under the MIT License.
#pragma warning disable 1634, 1691
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Internal.Host;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// Monad internal implementation of the ICommandRuntime2 interface
/// used for execution in the monad engine environment.
///
/// There will be one instance of this class for each cmdlet added to
/// a pipeline. When the cmdlet calls its WriteObject API, that API will call
/// the WriteObject implementation in this class which, in turn, calls
/// the downstream cmdlet.
/// </summary>
internal class MshCommandRuntime : ICommandRuntime2
{
#region private_members
/// <summary>
/// Gets/Set the execution context value for this runtime object.
/// </summary>
internal ExecutionContext Context { get; set; }
private SessionState _state = null;
internal InternalHost CBhost;
/// <summary>
/// The host object for this object.
/// </summary>
public PSHost Host { get; }
// Output pipes.
private Pipe _inputPipe;
private Pipe _outputPipe;
private Pipe _errorOutputPipe;
/// <summary>
/// IsClosed indicates to the Cmdlet whether its upstream partner
/// could still write more data to its incoming queue.
/// Note that there may still be data in the incoming queue.
/// </summary>
internal bool IsClosed { get; set; }
/// <summary>
/// True if we're not closed and the input pipe is non-null...
/// </summary>
internal bool IsPipelineInputExpected
{
get
{
// No objects in the input pipe
// The pipe is closed. So there can't be any more object
if (IsClosed && (_inputPipe == null || _inputPipe.Empty))
{
return false;
}
return true;
}
}
/// <summary>
/// This allows all success output to be set to a variable. Similar to the way -errorvariable sets
/// all errors to a variable name. Semantically this is equivalent to : cmd |set-var varname -passthru
/// but it should be MUCH faster as there is no binding that takes place.
/// </summary>
/// <exception cref="System.ArgumentNullException">
/// may not be set to null
/// </exception>
/// <remarks>
/// This is a common parameter via class CommonParameters.
/// </remarks>
internal string OutVariable { get; set; }
internal IList OutVarList { get { return _outVarList; } set { _outVarList = value; } }
private IList _outVarList = null;
internal PipelineProcessor PipelineProcessor { get; set; }
private readonly CommandInfo _commandInfo;
private readonly InternalCommand _thisCommand;
#endregion private_members
internal MshCommandRuntime(ExecutionContext context, CommandInfo commandInfo, InternalCommand thisCommand)
{
Context = context;
Host = context.EngineHostInterface;
this.CBhost = (InternalHost)context.EngineHostInterface;
_commandInfo = commandInfo;
_thisCommand = thisCommand;
LogPipelineExecutionDetail = InitShouldLogPipelineExecutionDetail();
}
/// <summary>
/// For diagnostic purposes.
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (_commandInfo != null)
return _commandInfo.ToString();
return "<NullCommandInfo>"; // does not require localization
}
private InvocationInfo _myInvocation;
/// <summary>
/// Return the invocation data object for this command.
/// </summary>
/// <value>The invocation object for this command.</value>
internal InvocationInfo MyInvocation
{
get { return _myInvocation ??= _thisCommand.MyInvocation; }
}
/// <summary>
/// Internal helper. Indicates whether stop has been requested on this command.
/// </summary>
internal bool IsStopping
{
get { return (this.PipelineProcessor != null && this.PipelineProcessor.Stopping); }
}
#region Write
// Trust: WriteObject needs to respect EmitTrustCategory
/// <summary>
/// Writes the object to the output pipe.
/// </summary>
/// <param name="sendToPipeline">
/// The object that needs to be written. This will be written as
/// a single object, even if it is an enumeration.
/// </param>
/// <exception cref="System.Management.Automation.PipelineStoppedException">
/// The pipeline has already been terminated, or was terminated
/// during the execution of this method.
/// The Cmdlet should generally just allow PipelineStoppedException
/// to percolate up to the caller of ProcessRecord etc.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// Not permitted at this time or from this thread.
/// WriteObject may only be called during a call to this Cmdlet's
/// implementation of ProcessRecord, BeginProcessing or EndProcessing,
/// and only from that thread.
/// </exception>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteObject(object,bool)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteError(ErrorRecord)"/>
public void WriteObject(object sendToPipeline)
{
// This check will be repeated in _WriteObjectSkipAllowCheck,
// but we want PipelineStoppedException to take precedence
// over InvalidOperationException if the pipeline has been
// closed.
ThrowIfStopping();
#if CORECLR
// SecurityContext is not supported in CoreCLR
DoWriteObject(sendToPipeline);
#else
if (UseSecurityContextRun)
{
if (PipelineProcessor == null || PipelineProcessor.SecurityContext == null)
throw PSTraceSource.NewInvalidOperationException(PipelineStrings.WriteNotPermitted);
ContextCallback delegateCallback =
new ContextCallback(DoWriteObject);
SecurityContext.Run(
PipelineProcessor.SecurityContext.CreateCopy(),
delegateCallback,
sendToPipeline);
}
else
{
DoWriteObject(sendToPipeline);
}
#endif
}
/// <exception cref="System.Management.Automation.PipelineStoppedException">
/// The pipeline has already been terminated, or was terminated
/// during the execution of this method.
/// The Cmdlet should generally just allow PipelineStoppedException
/// to percolate up to the caller of ProcessRecord etc.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// Not permitted at this time or from this thread
/// </exception>
private void DoWriteObject(object sendToPipeline)
{
ThrowIfWriteNotPermitted(true);
_WriteObjectSkipAllowCheck(sendToPipeline);
}
/// <summary>
/// Writes one or more objects to the output pipe.
/// If the object is a collection and the enumerateCollection flag
/// is true, the objects in the collection
/// will be written individually.
/// </summary>
/// <param name="sendToPipeline">
/// The object that needs to be written to the pipeline.
/// </param>
/// <param name="enumerateCollection">
/// true if the collection should be enumerated
/// </param>
/// <exception cref="System.Management.Automation.PipelineStoppedException">
/// The pipeline has already been terminated, or was terminated
/// during the execution of this method.
/// The Cmdlet should generally just allow PipelineStoppedException
/// to percolate up to the caller of ProcessRecord etc.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// Not permitted at this time or from this thread.
/// WriteObject may only be called during a call to this Cmdlet's
/// implementation of ProcessRecord, BeginProcessing or EndProcessing,
/// and only from that thread.
/// </exception>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteObject(object)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteError(ErrorRecord)"/>
public void WriteObject(object sendToPipeline, bool enumerateCollection)
{
if (!enumerateCollection)
{
WriteObject(sendToPipeline);
return;
}
// This check will be repeated in _WriteObjectsSkipAllowCheck,
// but we want PipelineStoppedException to take precedence
// over InvalidOperationException if the pipeline has been
// closed.
ThrowIfStopping();
#if CORECLR
// SecurityContext is not supported in CoreCLR
DoWriteEnumeratedObject(sendToPipeline);
#else
if (UseSecurityContextRun)
{
if (PipelineProcessor == null || PipelineProcessor.SecurityContext == null)
throw PSTraceSource.NewInvalidOperationException(PipelineStrings.WriteNotPermitted);
ContextCallback delegateCallback =
new ContextCallback(DoWriteObjects);
SecurityContext.Run(
PipelineProcessor.SecurityContext.CreateCopy(),
delegateCallback,
sendToPipeline);
}
else
{
DoWriteObjects(sendToPipeline);
}
#endif
}
/// <summary>
/// Writes an object enumerated from a collection to the output pipe.
/// </summary>
/// <param name="sendToPipeline">
/// The enumerated object that needs to be written to the pipeline.
/// </param>
/// <exception cref="System.Management.Automation.PipelineStoppedException">
/// The pipeline has already been terminated, or was terminated
/// during the execution of this method.
/// The Cmdlet should generally just allow PipelineStoppedException
/// to percolate up to the caller of ProcessRecord etc.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// Not permitted at this time or from this thread.
/// </exception>
private void DoWriteEnumeratedObject(object sendToPipeline)
{
// NOTICE-2004/06/08-JonN 959638
ThrowIfWriteNotPermitted(true);
_EnumerateAndWriteObjectSkipAllowCheck(sendToPipeline);
}
// Trust: public void WriteObject(object sendToPipeline, DataTrustCategory trustCategory); // enumerateCollection defaults to false
// Trust: public void WriteObject(object sendToPipeline, bool enumerateCollection, DataTrustCategory trustCategory);
// Variables needed to generate a unique SourceId for
// WriteProgress(ProgressRecord).
private static Int64 s_lastUsedSourceId /* = 0 */;
private Int64 _sourceId /* = 0 */;
/// <summary>
/// Display progress information.
/// </summary>
/// <param name="progressRecord">Progress information.</param>
/// <exception cref="System.Management.Automation.PipelineStoppedException">
/// The pipeline has already been terminated, or was terminated
/// during the execution of this method.
/// The Cmdlet should generally just allow PipelineStoppedException
/// to percolate up to the caller of ProcessRecord etc.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// Not permitted at this time or from this thread.
/// WriteProgress may only be called during a call to this Cmdlet's
/// implementation of ProcessRecord, BeginProcessing or EndProcessing,
/// and only from that thread.
/// </exception>
/// <remarks>
/// Use WriteProgress to display progress information about
/// the activity of your Cmdlet, when the operation of your Cmdlet
/// could potentially take a long time.
///
/// By default, progress output will
/// be displayed, although this can be configured with the
/// ProgressPreference shell variable.
/// </remarks>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteDebug(string)"/>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteWarning(string)"/>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteVerbose(string)"/>
public void WriteProgress(ProgressRecord progressRecord)
{
this.WriteProgress(progressRecord, false);
}
internal void WriteProgress(ProgressRecord progressRecord, bool overrideInquire)
{
// NTRAID#Windows Out Of Band Releases-918023-2005/08/22-JonN
ThrowIfStopping();
//
// WriteError/WriteObject have a check that prevents them to be called from outside
// Begin/Process/End. This is done because the Pipeline needs to be ready before these
// functions can be called.
//
// WriteDebug/Warning/Verbose/Process used to do the same check, even though it is not
// strictly needed. If we ever implement pipelines for these objects we may need to
// enforce the check again.
//
// See bug 583774 in the Windows 7 database for more details.
//
ThrowIfWriteNotPermitted(false);
// Bug909439: We need a unique sourceId to send to
// WriteProgress. The following logic ensures that
// there is a unique id for each Cmdlet instance.
if (_sourceId == 0)
{
_sourceId = Interlocked.Increment(ref s_lastUsedSourceId);
}
this.WriteProgress(_sourceId, progressRecord, overrideInquire);
}
/// <summary>
/// Displays progress output if enabled.
/// </summary>
/// <param name="sourceId">
/// Identifies which command is reporting progress
/// </param>
/// <param name="progressRecord">
/// Progress status to be displayed
/// </param>
/// <exception cref="System.Management.Automation.PipelineStoppedException">
/// The pipeline has already been terminated, or was terminated
/// during the execution of this method.
/// The Cmdlet should generally just allow PipelineStoppedException
/// to percolate up to the caller of ProcessRecord etc.
/// </exception>
/// <remarks>
/// If the pipeline is terminated due to ActionPreference.Stop
/// or ActionPreference.Inquire, this method will throw
/// <see cref="System.Management.Automation.PipelineStoppedException"/>,
/// but the command failure will ultimately be
/// <see cref="System.Management.Automation.ActionPreferenceStopException"/>,
/// </remarks>
public void WriteProgress(
Int64 sourceId,
ProgressRecord progressRecord)
{
WriteProgress(sourceId, progressRecord, false);
}
internal void WriteProgress(
Int64 sourceId,
ProgressRecord progressRecord,
bool overrideInquire)
{
if (progressRecord == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(progressRecord));
}
if (Host == null || Host.UI == null)
{
Diagnostics.Assert(false, "No host in CommandBase.WriteProgress()");
throw PSTraceSource.NewInvalidOperationException();
}
InternalHostUserInterface ui = Host.UI as InternalHostUserInterface;
ActionPreference preference = ProgressPreference;
if (overrideInquire && preference == ActionPreference.Inquire)
{
preference = ActionPreference.Continue;
}
if (WriteHelper_ShouldWrite(
preference, lastProgressContinueStatus))
{
// Break into the debugger if requested
if (preference == ActionPreference.Break)
{
CBhost?.Runspace?.Debugger?.Break(progressRecord);
}
ui.WriteProgress(sourceId, progressRecord);
}
lastProgressContinueStatus = WriteHelper(
null,
null,
preference,
lastProgressContinueStatus,
"ProgressPreference",
progressRecord.Activity);
}
/// <summary>
/// Display debug information.
/// </summary>
/// <param name="text">Debug output.</param>
/// <exception cref="System.Management.Automation.PipelineStoppedException">
/// The pipeline has already been terminated, or was terminated
/// during the execution of this method.
/// The Cmdlet should generally just allow PipelineStoppedException
/// to percolate up to the caller of ProcessRecord etc.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// Not permitted at this time or from this thread.
/// WriteDebug may only be called during a call to this Cmdlet's
/// implementation of ProcessRecord, BeginProcessing or EndProcessing,
/// and only from that thread.
/// </exception>
/// <remarks>
/// Use WriteDebug to display debug information on the inner workings
/// of your Cmdlet. By default, debug output will
/// not be displayed, although this can be configured with the
/// DebugPreference shell variable or the -Debug command-line option.
/// </remarks>
/// <remarks>
/// If the pipeline is terminated due to ActionPreference.Stop
/// or ActionPreference.Inquire, this method will throw
/// <see cref="System.Management.Automation.PipelineStoppedException"/>,
/// but the command failure will ultimately be
/// <see cref="System.Management.Automation.ActionPreferenceStopException"/>,
/// </remarks>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteVerbose(string)"/>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteWarning(string)"/>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteProgress(ProgressRecord)"/>
public void WriteDebug(string text)
{
WriteDebug(new DebugRecord(text));
}
/// <summary>
/// Display debug information.
/// </summary>
internal void WriteDebug(DebugRecord record, bool overrideInquire = false)
{
ActionPreference preference = DebugPreference;
if (overrideInquire && preference == ActionPreference.Inquire)
preference = ActionPreference.Continue;
if (WriteHelper_ShouldWrite(preference, lastDebugContinueStatus))
{
if (record.InvocationInfo == null)
{
record.SetInvocationInfo(MyInvocation);
}
// Break into the debugger if requested
if (preference == ActionPreference.Break)
{
CBhost?.Runspace?.Debugger?.Break(record);
}
if (DebugOutputPipe != null)
{
if (CBhost != null && CBhost.InternalUI != null &&
DebugOutputPipe.NullPipe)
{
// If redirecting to a null pipe, still write to
// information buffers.
CBhost.InternalUI.WriteDebugInfoBuffers(record);
}
// Set WriteStream so that the debug output is formatted correctly.
PSObject debugWrap = PSObject.AsPSObject(record);
debugWrap.WriteStream = WriteStreamType.Debug;
DebugOutputPipe.Add(debugWrap);
}
else
{
//
// If no pipe, write directly to host.
//
if (Host == null || Host.UI == null)
{
Diagnostics.Assert(false, "No host in CommandBase.WriteDebug()");
throw PSTraceSource.NewInvalidOperationException();
}
CBhost.InternalUI.TranscribeResult(StringUtil.Format(InternalHostUserInterfaceStrings.DebugFormatString, record.Message));
CBhost.InternalUI.WriteDebugRecord(record);
}
}
lastDebugContinueStatus = WriteHelper(
null,
null,
preference,
lastDebugContinueStatus,
"DebugPreference",
record.Message);
}
/// <summary>
/// Display verbose information.
/// </summary>
/// <param name="text">Verbose output.</param>
/// <exception cref="System.Management.Automation.PipelineStoppedException">
/// The pipeline has already been terminated, or was terminated
/// during the execution of this method.
/// The Cmdlet should generally just allow PipelineStoppedException
/// to percolate up to the caller of ProcessRecord etc.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// Not permitted at this time or from this thread.
/// WriteVerbose may only be called during a call to this Cmdlet's
/// implementation of ProcessRecord, BeginProcessing or EndProcessing,
/// and only from that thread.
/// </exception>
/// <remarks>
/// Use WriteVerbose to display more detailed information about
/// the activity of your Cmdlet. By default, verbose output will
/// not be displayed, although this can be configured with the
/// VerbosePreference shell variable
/// or the -Verbose and -Debug command-line options.
/// </remarks>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteDebug(string)"/>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteWarning(string)"/>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteProgress(ProgressRecord)"/>
public void WriteVerbose(string text)
{
WriteVerbose(new VerboseRecord(text));
}
/// <summary>
/// Display verbose information.
/// </summary>
internal void WriteVerbose(VerboseRecord record, bool overrideInquire = false)
{
ActionPreference preference = VerbosePreference;
if (overrideInquire && preference == ActionPreference.Inquire)
preference = ActionPreference.Continue;
if (WriteHelper_ShouldWrite(preference, lastVerboseContinueStatus))
{
if (record.InvocationInfo == null)
{
record.SetInvocationInfo(MyInvocation);
}
// Break into the debugger if requested
if (preference == ActionPreference.Break)
{
CBhost?.Runspace?.Debugger?.Break(record);
}
if (VerboseOutputPipe != null)
{
if (CBhost != null && CBhost.InternalUI != null &&
VerboseOutputPipe.NullPipe)
{
// If redirecting to a null pipe, still write to
// information buffers.
CBhost.InternalUI.WriteVerboseInfoBuffers(record);
}
// Add WriteStream so that the verbose output is formatted correctly.
PSObject verboseWrap = PSObject.AsPSObject(record);
verboseWrap.WriteStream = WriteStreamType.Verbose;
VerboseOutputPipe.Add(verboseWrap);
}
else
{
//
// If no pipe, write directly to host.
//
if (Host == null || Host.UI == null)
{
Diagnostics.Assert(false, "No host in CommandBase.WriteVerbose()");
throw PSTraceSource.NewInvalidOperationException();
}
CBhost.InternalUI.TranscribeResult(StringUtil.Format(InternalHostUserInterfaceStrings.VerboseFormatString, record.Message));
CBhost.InternalUI.WriteVerboseRecord(record);
}
}
lastVerboseContinueStatus = WriteHelper(
null,
null,
preference,
lastVerboseContinueStatus,
"VerbosePreference",
record.Message);
}
/// <summary>
/// Display warning information.
/// </summary>
/// <param name="text">Warning output.</param>
/// <exception cref="System.Management.Automation.PipelineStoppedException">
/// The pipeline has already been terminated, or was terminated
/// during the execution of this method.
/// The Cmdlet should generally just allow PipelineStoppedException
/// to percolate up to the caller of ProcessRecord etc.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// Not permitted at this time or from this thread.
/// WriteWarning may only be called during a call to this Cmdlet's
/// implementation of ProcessRecord, BeginProcessing or EndProcessing,
/// and only from that thread.
/// </exception>
/// <remarks>
/// Use WriteWarning to display warnings about
/// the activity of your Cmdlet. By default, warning output will
/// be displayed, although this can be configured with the
/// WarningPreference shell variable
/// or the -Verbose and -Debug command-line options.
/// </remarks>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteDebug(string)"/>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteVerbose(string)"/>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteProgress(ProgressRecord)"/>
public void WriteWarning(string text)
{
WriteWarning(new WarningRecord(text));
}
/// <summary>
/// Display warning information.
/// </summary>
internal void WriteWarning(WarningRecord record, bool overrideInquire = false)
{
ActionPreference preference = WarningPreference;
if (overrideInquire && preference == ActionPreference.Inquire)
preference = ActionPreference.Continue;
if (WriteHelper_ShouldWrite(preference, lastWarningContinueStatus))
{
if (record.InvocationInfo == null)
{
record.SetInvocationInfo(MyInvocation);
}
// Break into the debugger if requested
if (preference == ActionPreference.Break)
{
CBhost?.Runspace?.Debugger?.Break(record);
}
if (WarningOutputPipe != null)
{
if (CBhost != null && CBhost.InternalUI != null &&
WarningOutputPipe.NullPipe)
{
// If redirecting to a null pipe, still write to
// information buffers.
CBhost.InternalUI.WriteWarningInfoBuffers(record);
}
// Add WriteStream so that the warning output is formatted correctly.
PSObject warningWrap = PSObject.AsPSObject(record);
warningWrap.WriteStream = WriteStreamType.Warning;
WarningOutputPipe.AddWithoutAppendingOutVarList(warningWrap);
}
else
{
//
// If no pipe, write directly to host.
//
if (Host == null || Host.UI == null)
{
Diagnostics.Assert(false, "No host in CommandBase.WriteWarning()");
throw PSTraceSource.NewInvalidOperationException();
}
CBhost.InternalUI.TranscribeResult(StringUtil.Format(InternalHostUserInterfaceStrings.WarningFormatString, record.Message));
CBhost.InternalUI.WriteWarningRecord(record);
}
}
AppendWarningVarList(record);
lastWarningContinueStatus = WriteHelper(
null,
null,
preference,
lastWarningContinueStatus,
"WarningPreference",
record.Message);
}
/// <summary>
/// Display tagged object information.
/// </summary>
public void WriteInformation(InformationRecord informationRecord)
{
WriteInformation(informationRecord, false);
}
/// <summary>
/// Display tagged object information.
/// </summary>
internal void WriteInformation(InformationRecord record, bool overrideInquire = false)
{
ActionPreference preference = InformationPreference;
if (overrideInquire && preference == ActionPreference.Inquire)
preference = ActionPreference.Continue;
// Break into the debugger if requested
if (preference == ActionPreference.Break)
{
CBhost?.Runspace?.Debugger?.Break(record);
}
if (preference != ActionPreference.Ignore)
{
if (InformationOutputPipe != null)
{
if (CBhost != null && CBhost.InternalUI != null &&
InformationOutputPipe.NullPipe)
{
// If redirecting to a null pipe, still write to
// information buffers.
CBhost.InternalUI.WriteInformationInfoBuffers(record);
}
// Add WriteStream so that the information output is formatted correctly.
PSObject informationWrap = PSObject.AsPSObject(record);
informationWrap.WriteStream = WriteStreamType.Information;
InformationOutputPipe.Add(informationWrap);
}
else
{
//
// If no pipe, write directly to host.
//
if (Host == null || Host.UI == null)
{
throw PSTraceSource.NewInvalidOperationException("No host in CommandBase.WriteInformation()");
}
CBhost.InternalUI.WriteInformationRecord(record);
if ((record.Tags.Contains("PSHOST") && (!record.Tags.Contains("FORWARDED")))
|| (preference == ActionPreference.Continue))
{
HostInformationMessage hostOutput = record.MessageData as HostInformationMessage;
if (hostOutput != null)
{
string message = hostOutput.Message;
ConsoleColor? foregroundColor = null;
ConsoleColor? backgroundColor = null;
bool noNewLine = false;
if (hostOutput.ForegroundColor.HasValue)
{
foregroundColor = hostOutput.ForegroundColor.Value;
}
if (hostOutput.BackgroundColor.HasValue)
{
backgroundColor = hostOutput.BackgroundColor.Value;
}
if (hostOutput.NoNewLine.HasValue)
{
noNewLine = hostOutput.NoNewLine.Value;
}
if (foregroundColor.HasValue || backgroundColor.HasValue)
{
// It is possible for either one or the other to be empty if run from a
// non-interactive host, but only one was specified in Write-Host.
// So fill them with defaults if they are empty.
if (!foregroundColor.HasValue)
{
foregroundColor = ConsoleColor.Gray;
}
if (!backgroundColor.HasValue)
{
backgroundColor = ConsoleColor.Black;
}
if (noNewLine)
{
CBhost.InternalUI.Write(foregroundColor.Value, backgroundColor.Value, message);
}
else
{
CBhost.InternalUI.WriteLine(foregroundColor.Value, backgroundColor.Value, message);
}
}
else
{
if (noNewLine)
{
CBhost.InternalUI.Write(message);
}
else
{
CBhost.InternalUI.WriteLine(message);
}
}
}
else
{
CBhost.InternalUI.WriteLine(record.ToString());
}
}
}
// Both informational and PSHost-targeted messages are transcribed here.
// The only difference between these two is that PSHost-targeted messages are transcribed
// even if InformationAction is SilentlyContinue.
if (record.Tags.Contains("PSHOST") || (preference != ActionPreference.SilentlyContinue))
{
CBhost.InternalUI.TranscribeResult(record.ToString());
}
}
AppendInformationVarList(record);
lastInformationContinueStatus = WriteHelper(
null,
null,
preference,
lastInformationContinueStatus,
"InformationPreference",
record.ToString());
}
/// <summary>
/// Write text into pipeline execution log.
/// </summary>
/// <param name="text">Text to be written to log.</param>
/// <remarks>
/// Use WriteCommandDetail to write important information about cmdlet execution to
/// pipeline execution log.
///
/// If LogPipelineExecutionDetail is turned on, this information will be written
/// to monad log under log category "Pipeline execution detail"
/// </remarks>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteDebug(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteVerbose(string)"/>
/// <seealso cref="System.Management.Automation.ICommandRuntime.WriteProgress(ProgressRecord)"/>
public void WriteCommandDetail(string text)
{
this.PipelineProcessor.LogExecutionInfo(_thisCommand.MyInvocation, text);
}
internal bool LogPipelineExecutionDetail { get; } = false;
private bool InitShouldLogPipelineExecutionDetail()
{
CmdletInfo cmdletInfo = _commandInfo as CmdletInfo;
if (cmdletInfo != null)
{
if (string.Equals("Add-Type", cmdletInfo.Name, StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (cmdletInfo.Module == null && cmdletInfo.PSSnapIn != null)
{
return cmdletInfo.PSSnapIn.LogPipelineExecutionDetails;
}
if (cmdletInfo.PSSnapIn == null && cmdletInfo.Module != null)
{
return cmdletInfo.Module.LogPipelineExecutionDetails;
}
return false;
}
// Logging should be enabled for functions from modules also
FunctionInfo functionInfo = _commandInfo as FunctionInfo;
if (functionInfo != null && functionInfo.Module != null)
{
return functionInfo.Module.LogPipelineExecutionDetails;
}
return false;
}
/// <summary>
/// This allows all success output to be set to a variable, where the variable is reset for each item returned by
/// the cmdlet. Semantically this is equivalent to : cmd | % { $pipelineVariable = $_; (...) }
/// </summary>
internal string PipelineVariable { get; set; }
private PSVariable _pipelineVarReference = null;
internal void SetupOutVariable()
{
if (string.IsNullOrEmpty(this.OutVariable))
{
return;
}
EnsureVariableParameterAllowed();
// Handle the creation of OutVariable in the case of Out-Default specially,
// as it needs to handle much of its OutVariable support itself.
if (!OutVariable.StartsWith('+') &&
string.Equals("Out-Default", _commandInfo.Name, StringComparison.OrdinalIgnoreCase))
{
if (_state == null)
_state = new SessionState(Context.EngineSessionState);
IList oldValue = null;
oldValue = PSObject.Base(_state.PSVariable.GetValue(this.OutVariable)) as IList;
_outVarList = oldValue ?? new ArrayList();
if (_thisCommand is not PSScriptCmdlet)
{
this.OutputPipe.AddVariableList(VariableStreamKind.Output, _outVarList);
}
_state.PSVariable.Set(this.OutVariable, _outVarList);
}
else
{
SetupVariable(VariableStreamKind.Output, this.OutVariable, ref _outVarList);
}
}
internal void SetupPipelineVariable()
{
// This can't use the common SetupVariable implementation, as this needs to persist for an entire
// pipeline.
if (string.IsNullOrEmpty(this.PipelineVariable))
{
return;
}
EnsureVariableParameterAllowed();
if (_state == null)
_state = new SessionState(Context.EngineSessionState);
// Create the pipeline variable
_pipelineVarReference = new PSVariable(this.PipelineVariable);
_state.PSVariable.Set(_pipelineVarReference);
// Get the reference again in case we re-used one from the
// same scope.
_pipelineVarReference = _state.PSVariable.Get(this.PipelineVariable);
if (_thisCommand is not PSScriptCmdlet)
{
this.OutputPipe.SetPipelineVariable(_pipelineVarReference);
}
}
/// <summary>
/// Configures the number of objects to buffer before calling the downstream Cmdlet.
/// </summary>
/// <remarks>