forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMshHostUserInterface.cs
More file actions
1273 lines (1145 loc) · 57.8 KB
/
Copy pathMshHostUserInterface.cs
File metadata and controls
1273 lines (1145 loc) · 57.8 KB
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. All rights reserved.
--********************************************************************/
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Security;
using System.Globalization;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell.Commands;
using System.Threading.Tasks;
namespace System.Management.Automation.Host
{
/// <summary>
///
/// Defines the properties and facilities providing by an hosting application deriving from
/// <see cref="System.Management.Automation.Host.PSHost"/> that offers dialog-oriented and
/// line-oriented interactive features.
///
/// </summary>
/// <seealso cref="System.Management.Automation.Host.PSHost"/>
/// <seealso cref="System.Management.Automation.Host.PSHostRawUserInterface"/>
public abstract class PSHostUserInterface
{
/// <summary>
/// Gets hosting application's implementation of the
/// <see cref="System.Management.Automation.Host.PSHostRawUserInterface"/> abstract base class
/// that implements that class.
/// </summary>
/// <value>
/// A reference to an instance of the hosting application's implementation of a class derived from
/// <see cref="System.Management.Automation.Host.PSHostUserInterface"/>, or null to indicate that
/// low-level user interaction is not supported.
/// </value>
public abstract System.Management.Automation.Host.PSHostRawUserInterface RawUI
{
get;
}
/// <summary>
/// Returns true for hosts that support VT100 like virtual terminals.
/// </summary>
public virtual bool SupportsVirtualTerminal { get { return false; } }
#region Line-oriented interaction
/// <summary>
/// Reads characters from the console until a newline (a carriage return) is encountered.
/// </summary>
/// <returns>
/// The characters typed by the user.
/// </returns>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLineAsSecureString"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string, System.Management.Automation.PSCredentialTypes, System.Management.Automation.PSCredentialUIOptions)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/>
public abstract string ReadLine();
/// <summary>
/// Same as ReadLine, except that the result is a SecureString, and that the input is not echoed to the user while it is
/// collected (or is echoed in some obfuscated way, such as showing a dot for each character).
/// </summary>
/// <returns>
/// The characters typed by the user in an encrypted form.
/// </returns>
/// <remarks>
/// Note that credentials (a user name and password) should be gathered with
/// <see cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string)"/>
/// <see cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string, System.Management.Automation.PSCredentialTypes, System.Management.Automation.PSCredentialUIOptions)"/>
/// </remarks>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLine"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string, System.Management.Automation.PSCredentialTypes, System.Management.Automation.PSCredentialUIOptions)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/>
public abstract SecureString ReadLineAsSecureString();
/// <summary>
/// Writes characters to the screen buffer. Does not append a carriage return.
/// <!-- Here we choose to just offer string parameters rather than the 18 overloads from TextWriter -->
/// </summary>
/// <param name="value">
/// The characters to be written. null is not allowed.
/// </param>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(ConsoleColor, ConsoleColor, string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine()"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(System.ConsoleColor, System.ConsoleColor, string)"/>
public abstract void Write(string value);
/// <summary>
/// Same as <see cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/>,
/// except that colors can be specified.
/// </summary>
/// <param name="foregroundColor">
/// The foreground color to display the text with.
/// </param>
/// <param name="backgroundColor">
/// The foreground color to display the text with.
/// </param>
/// <param name="value">
/// The characters to be written. null is not allowed.
/// </param>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine()"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(System.ConsoleColor, System.ConsoleColor, string)"/>
public abstract void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value);
/// <summary>
/// The default implementation writes a carriage return to the screen buffer.
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(System.ConsoleColor, System.ConsoleColor, string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(System.ConsoleColor, System.ConsoleColor, string)"/>
/// </summary>
public virtual void WriteLine()
{
WriteLine("");
}
/// <summary>
/// Writes characters to the screen buffer, and appends a carriage return.
/// </summary>
/// <param name="value">
/// The characters to be written. null is not allowed.
/// </param>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(System.ConsoleColor, System.ConsoleColor, string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine()"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(System.ConsoleColor, System.ConsoleColor, string)"/>
public abstract void WriteLine(string value);
/// <summary>
/// Same as <see cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/>,
/// except that colors can be specified.
/// </summary>
/// <param name="foregroundColor">
/// The foreground color to display the text with.
/// </param>
/// <param name="backgroundColor">
/// The foreground color to display the text with.
/// </param>
/// <param name="value">
/// The characters to be written. null is not allowed.
/// </param>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(System.ConsoleColor, System.ConsoleColor, string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine()"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/>
public virtual void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
{
// #pragma warning disable 56506
// expressly not checking for value == null so that attempts to write a null cause an exception
if ((value != null) && (value.Length != 0))
{
Write(foregroundColor, backgroundColor, value);
}
Write("\n");
// #pragma warning restore 56506
}
/// <summary>
/// Writes a line to the "error display" of the host, as opposed to the "output display," which is
/// written to by the variants of
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(System.ConsoleColor, System.ConsoleColor, string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine()"/> and
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/>
/// </summary>
/// <param name="value">
/// The characters to be written.
/// </param>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(System.ConsoleColor, System.ConsoleColor, string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine()"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/>
public abstract void WriteErrorLine(string value);
/// <summary>
/// Invoked by <see cref="System.Management.Automation.Cmdlet.WriteDebug"/> to display a debugging message
/// to the user.
/// </summary>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteProgress"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteVerboseLine"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteWarningLine"/>
public abstract void WriteDebugLine(string message);
/// <summary>
/// Invoked by <see cref="System.Management.Automation.Cmdlet.WriteProgress(Int64, System.Management.Automation.ProgressRecord)"/> to display a progress record.
/// </summary>
/// <param name="sourceId">
/// Unique identifier of the source of the record. An int64 is used because typically, the 'this' pointer of
/// the command from whence the record is originating is used, and that may be from a remote Runspace on a 64-bit
/// machine.
/// </param>
/// <param name="record">
/// The record being reported to the host.
/// </param>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteDebugLine"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteVerboseLine"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteWarningLine"/>
public abstract void WriteProgress(Int64 sourceId, ProgressRecord record);
/// <summary>
/// Invoked by <see cref="System.Management.Automation.Cmdlet.WriteVerbose"/> to display a verbose processing message to the user.
/// </summary>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteDebugLine"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteProgress"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteWarningLine"/>
public abstract void WriteVerboseLine(string message);
/// <summary>
/// Invoked by <see cref="System.Management.Automation.Cmdlet.WriteWarning"/> to display a warning processing message to the user.
/// </summary>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteDebugLine"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteProgress"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteVerboseLine"/>
public abstract void WriteWarningLine(string message);
/// <summary>
/// Invoked by <see cref="System.Management.Automation.Cmdlet.WriteInformation(InformationRecord)"/> to give the host a chance to intercept
/// informational messages. These should not be displayed to the user by default, but may be useful to display in
/// a separate area of the user interface.
/// </summary>
public virtual void WriteInformation(InformationRecord record) { }
// Gets the state associated with PowerShell transcription.
//
// Ideally, this would be associated with the host instance, but remoting recycles host instances
// for each command that gets invoked (so that it can keep track of the order of commands and their
// output.) Therefore, we store this transcripton data in the runspace. However, the
// Runspace.DefaultRunspace property isn't always available (i.e.: when the pipeline is being set up),
// so we have to cache it the first time it becomes available.
private TranscriptionData TranscriptionData
{
get
{
// If we have access to a runspace, use the transcription data for that runspace.
// This is important when you have multiple runspaces within a host.
LocalRunspace localRunspace = Runspace.DefaultRunspace as LocalRunspace;
if (localRunspace != null)
{
_volatileTranscriptionData = localRunspace.TranscriptionData;
if (_volatileTranscriptionData != null)
{
return _volatileTranscriptionData;
}
}
// Otherwise, use the last stored transcription data. This will let us transcribe
// errors where the runspace has gone away.
if (_volatileTranscriptionData != null)
{
return _volatileTranscriptionData;
}
TranscriptionData temporaryTranscriptionData = new TranscriptionData();
return temporaryTranscriptionData;
}
}
private TranscriptionData _volatileTranscriptionData;
/// <summary>
/// Transcribes a command being invoked
/// </summary>
/// <param name="commandText">The text of the command being invoked.</param>
/// <param name="invocation">The invocation info of the command being transcribed.</param>
internal void TranscribeCommand(string commandText, InvocationInfo invocation)
{
if (ShouldIgnoreCommand(commandText, invocation))
{
return;
}
if (IsTranscribing)
{
// We don't actually log the output here, because there may be multiple command invocations
// in a single input - especially in the case of API logging, which logs the command and
// its parameters as separate calls.
// Instead, we add this to the 'pendingOutput' collection, which we flush when either
// the command generates output, or when we are told to invoke ignore the next command.
foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend<TranscriptionOption>(TranscriptionData.SystemTranscript))
{
if (transcript != null)
{
lock (transcript.OutputToLog)
{
if (transcript.OutputToLog.Count == 0)
{
if (transcript.IncludeInvocationHeader)
{
transcript.OutputToLog.Add("**********************");
transcript.OutputToLog.Add(
String.Format(
Globalization.CultureInfo.InvariantCulture, InternalHostUserInterfaceStrings.CommandStartTime,
DateTime.Now.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture)));
transcript.OutputToLog.Add("**********************");
}
transcript.OutputToLog.Add(TranscriptionData.PromptText + commandText);
}
else
{
transcript.OutputToLog.Add(">> " + commandText);
}
}
}
}
}
}
private bool ShouldIgnoreCommand(string logElement, InvocationInfo invocation)
{
string commandName = logElement;
if (invocation != null)
{
commandName = invocation.InvocationName;
// Do not transcribe Out-Default
CmdletInfo invocationCmdlet = invocation.MyCommand as CmdletInfo;
if (invocationCmdlet != null)
{
if (invocationCmdlet.ImplementingType == typeof(Microsoft.PowerShell.Commands.OutDefaultCommand))
{
// We will ignore transcribing the command itself, but not call the IgnoreCommand() method
// (because that will ignore the results)
return true;
}
}
// Don't log internal commands to the transcript.
if (invocation.CommandOrigin == CommandOrigin.Internal)
{
IgnoreCommand(logElement, invocation);
return true;
}
}
// Don't log helper commands to the transcript
string[] helperCommands = { "TabExpansion2", "prompt", "TabExpansion", "PSConsoleHostReadline" };
foreach (string helperCommand in helperCommands)
{
if (String.Equals(helperCommand, commandName, StringComparison.OrdinalIgnoreCase))
{
IgnoreCommand(logElement, invocation);
// Record that this is a helper command. In this case, we ignore even the results
// from Out-Default
TranscriptionData.IsHelperCommand = true;
return true;
}
}
return false;
}
/// <summary>
/// Signals that a command being invoked (and its output) should be ignored.
/// </summary>
/// <param name="commandText">The text of the command being invoked.</param>
/// <param name="invocation">The invocation info of the command being transcribed.</param>
internal void IgnoreCommand(string commandText, InvocationInfo invocation)
{
TranscribeCommandComplete(null);
if (TranscriptionData.CommandBeingIgnored == null)
{
TranscriptionData.CommandBeingIgnored = commandText;
TranscriptionData.IsHelperCommand = false;
if ((invocation != null) && (invocation.MyCommand != null))
{
TranscriptionData.CommandBeingIgnored = invocation.MyCommand.Name;
}
}
}
/// <summary>
/// Flag to determine whether the host is in "Transcribe Only" mode,
/// so that when content is sent through Out-Default it doesn't
/// make it to the actual host.
/// </summary>
internal bool TranscribeOnly { get; set; }
/// <summary>
/// Flag to determine whether the host is transcribing.
/// </summary>
internal bool IsTranscribing
{
get
{
CheckSystemTranscript();
return (TranscriptionData.Transcripts.Count > 0) || (TranscriptionData.SystemTranscript != null);
}
}
private void CheckSystemTranscript()
{
lock (TranscriptionData)
{
if (TranscriptionData.SystemTranscript == null)
{
TranscriptionData.SystemTranscript = PSHostUserInterface.GetSystemTranscriptOption(TranscriptionData.SystemTranscript);
if (TranscriptionData.SystemTranscript != null)
{
LogTranscriptHeader(null, TranscriptionData.SystemTranscript);
}
}
}
}
internal void StartTranscribing(string path, System.Management.Automation.Remoting.PSSenderInfo senderInfo, bool includeInvocationHeader)
{
TranscriptionOption transcript = new TranscriptionOption();
transcript.Path = path;
transcript.IncludeInvocationHeader = includeInvocationHeader;
TranscriptionData.Transcripts.Add(transcript);
LogTranscriptHeader(senderInfo, transcript);
}
private void LogTranscriptHeader(System.Management.Automation.Remoting.PSSenderInfo senderInfo, TranscriptionOption transcript)
{
string username = Environment.UserDomainName + "\\" + Environment.UserName;
string runAsUser = username;
if (senderInfo != null)
{
username = senderInfo.UserInfo.Identity.Name;
}
// Add bits from PSVersionTable
StringBuilder psVersionInfo = new StringBuilder();
Hashtable versionInfo = PSVersionInfo.GetPSVersionTable();
foreach (string versionKey in versionInfo.Keys)
{
Object value = versionInfo[versionKey];
if (value != null)
{
var arrayValue = value as object[];
string valueString = arrayValue != null ? string.Join(", ", arrayValue) : value.ToString();
psVersionInfo.AppendLine(versionKey + ": " + valueString);
}
}
// Transcribe the transcript header
string format = InternalHostUserInterfaceStrings.TranscriptPrologue;
string line =
String.Format(
Globalization.CultureInfo.InvariantCulture,
format,
DateTime.Now,
username,
runAsUser,
Environment.MachineName,
Environment.OSVersion.VersionString,
String.Join(" ", Environment.GetCommandLineArgs()),
System.Diagnostics.Process.GetCurrentProcess().Id,
psVersionInfo.ToString().TrimEnd()
);
lock (transcript.OutputToLog)
{
transcript.OutputToLog.Add(line);
}
TranscribeCommandComplete(null);
}
internal string StopTranscribing()
{
if (TranscriptionData.Transcripts.Count == 0)
{
throw new PSInvalidOperationException(InternalHostUserInterfaceStrings.HostNotTranscribing);
}
TranscriptionOption stoppedTranscript = TranscriptionData.Transcripts[TranscriptionData.Transcripts.Count - 1];
LogTranscriptFooter(stoppedTranscript);
stoppedTranscript.Dispose();
TranscriptionData.Transcripts.Remove(stoppedTranscript);
return stoppedTranscript.Path;
}
private void LogTranscriptFooter(TranscriptionOption stoppedTranscript)
{
// Transcribe the transcript epilogue
try
{
string message = String.Format(
Globalization.CultureInfo.InvariantCulture,
InternalHostUserInterfaceStrings.TranscriptEpilogue, DateTime.Now);
lock (stoppedTranscript.OutputToLog)
{
stoppedTranscript.OutputToLog.Add(message);
}
TranscribeCommandComplete(null);
}
catch (Exception e)
{
// Ignoring errors when stopping transcription (i.e.: file in use, access denied)
// since this is probably handling exactly that error.
CommandProcessorBase.CheckForSevereException(e);
}
}
internal void StopAllTranscribing()
{
TranscribeCommandComplete(null);
while (TranscriptionData.Transcripts.Count > 0)
{
StopTranscribing();
}
lock (TranscriptionData)
{
if (TranscriptionData.SystemTranscript != null)
{
LogTranscriptFooter(TranscriptionData.SystemTranscript);
TranscriptionData.SystemTranscript.Dispose();
TranscriptionData.SystemTranscript = null;
lock (s_systemTranscriptLock)
{
systemTranscript = null;
}
}
}
}
/// <summary>
/// Transcribes the supplied result text to the transcription buffer.
/// </summary>
/// <param name="sourceRunspace">The runspace that was used to generate this result, if it is not the current runspace.</param>
/// <param name="resultText">The text to be transcribed.</param>
internal void TranscribeResult(Runspace sourceRunspace, string resultText)
{
if (IsTranscribing)
{
// If the runspace that this result applies to is not the current runspace, update Runspace.DefaultRunspace
// so that the transcript paths / etc. will be available to the TranscriptionData accessor.
Runspace originalDefaultRunspace = null;
if (sourceRunspace != null)
{
originalDefaultRunspace = Runspace.DefaultRunspace;
Runspace.DefaultRunspace = sourceRunspace;
}
try
{
// If we're ignoring a command, ignore its output.
if (TranscriptionData.CommandBeingIgnored != null)
{
// If we're ignoring a prompt, capture the value
if (String.Equals("prompt", TranscriptionData.CommandBeingIgnored, StringComparison.OrdinalIgnoreCase))
{
TranscriptionData.PromptText = resultText;
}
return;
}
resultText = resultText.TrimEnd();
foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend<TranscriptionOption>(TranscriptionData.SystemTranscript))
{
if (transcript != null)
{
lock (transcript.OutputToLog)
{
transcript.OutputToLog.Add(resultText);
}
}
}
}
finally
{
if (originalDefaultRunspace != null)
{
Runspace.DefaultRunspace = originalDefaultRunspace;
}
}
}
}
/// <summary>
/// Transcribes the supplied result text to the transcription buffer.
/// </summary>
/// <param name="resultText">The text to be transcribed.</param>
internal void TranscribeResult(string resultText)
{
TranscribeResult(null, resultText);
}
/// <summary>
/// Transcribes / records the completion of a command
/// </summary>
/// <param name="invocation"></param>
internal void TranscribeCommandComplete(InvocationInfo invocation)
{
FlushPendingOutput();
if (invocation != null)
{
// If we're ignoring a command that was internal, we still want the
// results of Out-Default. However, if it was a host helper command,
// ignore all output (including Out-Default)
string commandNameToCheck = TranscriptionData.CommandBeingIgnored;
if (TranscriptionData.IsHelperCommand)
{
commandNameToCheck = "Out-Default";
}
// If we're completing a command that we were ignoring, start transcribing results / etc. again.
if ((TranscriptionData.CommandBeingIgnored != null) &&
(invocation != null) && (invocation.MyCommand != null) &&
String.Equals(commandNameToCheck, invocation.MyCommand.Name, StringComparison.OrdinalIgnoreCase))
{
TranscriptionData.CommandBeingIgnored = null;
TranscriptionData.IsHelperCommand = false;
}
}
}
internal void TranscribePipelineComplete()
{
FlushPendingOutput();
TranscriptionData.CommandBeingIgnored = null;
TranscriptionData.IsHelperCommand = false;
}
private void FlushPendingOutput()
{
foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend<TranscriptionOption>(TranscriptionData.SystemTranscript))
{
if (transcript != null)
{
lock (transcript.OutputToLog)
{
if (transcript.OutputToLog.Count == 0)
{
continue;
}
lock (transcript.OutputBeingLogged)
{
bool alreadyLogging = transcript.OutputBeingLogged.Count > 0;
transcript.OutputBeingLogged.AddRange(transcript.OutputToLog);
transcript.OutputToLog.Clear();
// If there is already a thread trying to log output, add this output to its buffer
// and don't start a new thread.
if (alreadyLogging)
{
continue;
}
}
}
// Do the actual writing in the background so that it doesn't hold up the UI thread.
Task writer = Task.Run(() =>
{
// System transcripts can have high contention. Do exponential back-off on writing
// if needed.
int delay = new Random().Next(10) + 1;
bool written = false;
while (!written)
{
try
{
string baseDirectory = Path.GetDirectoryName(transcript.Path);
if (!Directory.Exists(baseDirectory))
{
Directory.CreateDirectory(baseDirectory);
}
transcript.FlushContentToDisk();
written = true;
}
catch (IOException)
{
System.Threading.Thread.Sleep(delay);
}
catch (UnauthorizedAccessException)
{
System.Threading.Thread.Sleep(delay);
}
// If we are trying to log, but weren't able too, back of the sleep.
// If we're already sleeping for 1 second between tries, then just continue
// at this pace until the write is successful.
if (delay < 1000)
{
delay *= 2;
}
}
});
}
}
}
#endregion Line-oriented interaction
# region Dialog-oriented Interaction
/// <summary>
/// Constructs a 'dialog' where the user is presented with a number of fields for which to supply values.
/// </summary>
/// <param name="caption">
/// Caption to preceed or title the prompt. E.g. "Parameters for get-foo (instance 1 of 2)"
/// </param>
/// <param name="message">
/// A text description of the set of fields to be prompt.
/// </param>
/// <param name="descriptions">
/// Array of FieldDescriptions that contain information about each field to be prompted for.
/// </param>
/// <returns>
/// A Dictionary object with results of prompting. The keys are the field names from the FieldDescriptions, the values
/// are objects representing the values of the corresponding fields as collected from the user. To the extent possible,
/// the host should return values of the type(s) identified in the FieldDescription. When that is not possible (for
/// example, the type is not avaiable to the host), the host should return the value as a string.
/// </returns>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLine"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLineAsSecureString"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string, System.Management.Automation.PSCredentialTypes, System.Management.Automation.PSCredentialUIOptions)"/>
public abstract Dictionary<String, PSObject> Prompt(string caption, string message, Collection<FieldDescription> descriptions);
/// <summary>
/// Prompt for credentials.
/// <!--In future, when we have Credential object from the security team,
/// this function will be modified to prompt using secure-path
/// if so configured.-->
/// </summary>
/// <summary>
/// Prompt for credential.
/// </summary>
/// <param name="caption">
/// Caption for the message.
/// </param>
/// <param name="message">
/// Text description for the credential to be prompt.
/// </param>
/// <param name="userName">
/// Name of the user whose credential is to be prompted for. If set to null or empty
/// string, the function will prompt for user name first.
/// </param>
/// <param name="targetName">
/// Name of the target for which the credential is being collected.
/// </param>
/// <returns>
/// User input credential.
/// </returns>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLine"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLineAsSecureString"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string, System.Management.Automation.PSCredentialTypes, System.Management.Automation.PSCredentialUIOptions)"/>
public abstract PSCredential PromptForCredential(string caption, string message,
string userName, string targetName
);
/// <summary>
/// Prompt for credential.
/// </summary>
/// <param name="caption">
/// Caption for the message.
/// </param>
/// <param name="message">
/// Text description for the credential to be prompt.
/// </param>
/// <param name="userName">
/// Name of the user whose credential is to be prompted for. If set to null or empty
/// string, the function will prompt for user name first.
/// </param>
/// <param name="targetName">
/// Name of the target for which the credential is being collected.
/// </param>
/// <param name="allowedCredentialTypes">
/// Types of credential can be supplied by the user.
/// </param>
/// <param name="options">
/// Options that control the credential gathering UI behavior
/// </param>
/// <returns>
/// User input credential.
/// </returns>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLine"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLineAsSecureString"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string)"/>
public abstract PSCredential PromptForCredential(string caption, string message,
string userName, string targetName, PSCredentialTypes allowedCredentialTypes,
PSCredentialUIOptions options
);
/// <summary>
/// Presents a dialog allowing the user to choose an option from a set of options.
/// </summary>
/// <param name="caption">
/// Caption to preceed or title the prompt. E.g. "Parameters for get-foo (instance 1 of 2)"
/// </param>
/// <param name="message">
/// A message that describes what the choice is for.
/// </param>
/// <param name="choices">
/// An Collection of ChoiceDescription objects that describe each choice.
/// </param>
/// <param name="defaultChoice">
/// The index of the label in the choices collection element to be presented to the user as the default choice. -1
/// means "no default". Must be a valid index.
/// </param>
/// <returns>
/// The index of the choices element that corresponds to the option selected.
/// </returns>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLine"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLineAsSecureString"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string)"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string, System.Management.Automation.PSCredentialTypes, System.Management.Automation.PSCredentialUIOptions)"/>
public abstract int PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, int defaultChoice);
#endregion Dialog-oriented interaction
/// <summary>
/// Creates a new instance of the PSHostUserInterface class
/// </summary>
protected PSHostUserInterface()
{
CheckSystemTranscript();
}
/// <summary>
/// Helper to transcribe an error through formatting and output.
/// </summary>
/// <param name="context">The Execution Context</param>
/// <param name="invocation">The invocation info associated with the record</param>
/// <param name="errorWrap">The error record</param>
internal void TranscribeError(ExecutionContext context, InvocationInfo invocation, PSObject errorWrap)
{
context.InternalHost.UI.TranscribeCommandComplete(invocation);
InitialSessionState minimalState = InitialSessionState.CreateDefault2();
Collection<PSObject> results = PowerShell.Create(minimalState).AddCommand("Out-String").Invoke(
new List<PSObject>() { errorWrap });
TranscribeResult(results[0].ToString());
}
/// <summary>
/// Get Module Logging information from the registry.
/// </summary>
internal static TranscriptionOption GetSystemTranscriptOption(TranscriptionOption currentTranscript)
{
Dictionary<string, object> groupPolicySettings = Utils.GetGroupPolicySetting("Transcription", Utils.RegLocalMachineThenCurrentUser);
if (groupPolicySettings != null)
{
// If we have an existing system transcript for this process, use that.
// Otherwise, populate the static variable with the result of the group policy setting.
//
// This way, multiple runspaces opened by the same process will share the same transcript.
lock (s_systemTranscriptLock)
{
if (systemTranscript == null)
{
systemTranscript = PSHostUserInterface.GetTranscriptOptionFromSettings(groupPolicySettings, currentTranscript);
}
}
}
return systemTranscript;
}
internal static TranscriptionOption systemTranscript = null;
private static Object s_systemTranscriptLock = new Object();
private static TranscriptionOption GetTranscriptOptionFromSettings(Dictionary<string, object> settings, TranscriptionOption currentTranscript)
{
TranscriptionOption transcript = null;
object keyValue = null;
if (settings.TryGetValue("EnableTranscripting", out keyValue))
{
if (String.Equals(keyValue.ToString(), "1", StringComparison.OrdinalIgnoreCase))
{
if (currentTranscript != null)
{
return currentTranscript;
}
transcript = new TranscriptionOption();
// Pull out the transcript path
object outputDirectoryValue = null;
if (settings.TryGetValue("OutputDirectory", out outputDirectoryValue))
{
string outputDirectoryString = outputDirectoryValue as string;
transcript.Path = GetTranscriptPath(outputDirectoryString, true);
}
else
{
transcript.Path = GetTranscriptPath();
}
// Pull out the "enable invocation header"
object enableInvocationHeaderValue = null;
if (settings.TryGetValue("EnableInvocationHeader", out enableInvocationHeaderValue))
{
if (String.Equals("1", enableInvocationHeaderValue.ToString(), StringComparison.OrdinalIgnoreCase))
{
transcript.IncludeInvocationHeader = true;
}
}
}
}
return transcript;
}
internal static string GetTranscriptPath()
{
string baseDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
return GetTranscriptPath(baseDirectory, false);
}
internal static string GetTranscriptPath(string baseDirectory, bool includeDate)
{
if (String.IsNullOrEmpty(baseDirectory))
{
baseDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
else
{
if (!Path.IsPathRooted(baseDirectory))
{
baseDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
baseDirectory);
}
}
if (includeDate)
{
baseDirectory = Path.Combine(baseDirectory, DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture));
}
// transcriptPath includes some randomness so that files can be collected on a central share,
// and an attacker can't guess the filename and read the contents if the ACL was poor.
// After testing, a computer can do about 10,000 remote path tests per second. So 6
// bytes of randomness (2^48 = 2.8e14) would take an attacker about 891 years to guess
// a filename (assuming they knew the time the transcript was started).
// (5 bytes = 3 years, 4 bytes = about a month)
byte[] randomBytes = new byte[6];
System.Security.Cryptography.RandomNumberGenerator.Create().GetBytes(randomBytes);
string filename = String.Format(
Globalization.CultureInfo.InvariantCulture,
"PowerShell_transcript.{0}.{1}.{2:yyyyMMddHHmmss}.txt",
Environment.MachineName,
Convert.ToBase64String(randomBytes).Replace('/', '_'),
DateTime.Now);
string transcriptPath = System.IO.Path.Combine(baseDirectory, filename);
return transcriptPath;
}
}
// Holds runspace-wide transcription data / settings for PowerShell transcription
internal class TranscriptionData
{
internal TranscriptionData()
{
Transcripts = new List<TranscriptionOption>();
SystemTranscript = null;
CommandBeingIgnored = null;
IsHelperCommand = false;
PromptText = "PS>";
}
internal List<TranscriptionOption> Transcripts
{
get;
private set;
}
internal TranscriptionOption SystemTranscript { get; set; }