forked from PowerShell/PowerShell
/
ImplicitRemotingCommands.cs
3150 lines (2624 loc) · 121 KB
/
ImplicitRemotingCommands.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.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
using PowerShell = System.Management.Automation.PowerShell;
/// <summary>
/// This class implements Export-PSSession cmdlet.
/// Spec: TBD.
/// </summary>
[Cmdlet(VerbsData.Export, "PSSession", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096604")]
[OutputType(typeof(FileInfo))]
public sealed class ExportPSSessionCommand : ImplicitRemotingCommandBase
{
/// <summary>
/// Version of the script generator used (by this Export-PSSession cmdlet) to generate psm1 and psd1 files.
/// Generated script checks this version to see if it needs to be regenerated. There are 2 situations where this is needed
/// 1. the script needs to be regenerated because a bug fix made previous versions incompatible with the rest of the system (i.e. with ObjectModelWrapper).
/// 2. ths script needs to be regenerated because a security vulnerability was found inside generated code (there is no way to service generated code, but we can service the dll that reports the version that the generated script checks against).
/// </summary>
public static Version VersionOfScriptGenerator { get { return ImplicitRemotingCodeGenerator.VersionOfScriptWriter; } }
#region Parameters
/// <summary>
/// Mandatory file name to write to.
/// </summary>
[Parameter(Mandatory = true, Position = 1)]
[ValidateNotNullOrEmpty]
[Alias("PSPath", "ModuleName")]
public string OutputModule { get; set; }
/// <summary>
/// Property that sets force parameter.
/// </summary>
[Parameter]
public SwitchParameter Force
{
get
{
return new SwitchParameter(_force);
}
set
{
_force = value.IsPresent;
}
}
private bool _force;
/// <summary>
/// Encoding optional flag.
/// </summary>
[Parameter]
[ArgumentToEncodingTransformationAttribute()]
[ArgumentEncodingCompletionsAttribute]
[ValidateNotNullOrEmpty]
public Encoding Encoding
{
get
{
return _encoding;
}
set
{
EncodingConversion.WarnIfObsolete(this, value);
_encoding = value;
}
}
private Encoding _encoding = ClrFacade.GetDefaultEncoding();
#endregion Parameters
#region Implementation
private const string getChildItemScript = @"
param($path)
Get-ChildItem -LiteralPath $path
";
private const string copyItemScript = @"
param($sourcePath, $destinationPath)
Copy-Item -Recurse $sourcePath\\* -Destination $destinationPath\\
Remove-item $sourcePath -Recurse -Force
";
private void DisplayDirectory(List<string> generatedFiles)
{
ScriptBlock script = this.Context.Engine.ParseScriptBlock(getChildItemScript, false);
Collection<PSObject> results = script.Invoke(new object[] { generatedFiles.ToArray() });
foreach (PSObject o in results)
{
this.WriteObject(o);
}
}
/// <summary>
/// Performs initialization of cmdlet execution.
/// </summary>
protected override void BeginProcessing()
{
// Module and FullyQualifiedModule should not be specified at the same time.
// Throw out terminating error if this is the case.
if (IsModuleSpecified && IsFullyQualifiedModuleSpecified)
{
string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, nameof(Module), nameof(FullyQualifiedModule));
ErrorRecord error = new(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null);
ThrowTerminatingError(error);
}
DirectoryInfo directory = PathUtils.CreateModuleDirectory(this, this.OutputModule, this.Force.IsPresent);
// Creating a temporary directory where files will be created.
// Then, copy the files from this location to the location specified in OutputModule
// We are doing this since temporary locations in user directory are more secure.
DirectoryInfo tempDirectory = PathUtils.CreateTemporaryDirectory();
Dictionary<string, string> alias2resolvedCommandName;
List<CommandMetadata> listOfCommandMetadata = this.GetRemoteCommandMetadata(out alias2resolvedCommandName);
List<ExtendedTypeDefinition> listOfFormatData = this.GetRemoteFormatData();
List<string> generatedFiles = GenerateProxyModule(
tempDirectory,
Path.GetFileName(directory.FullName),
Encoding,
_force,
listOfCommandMetadata,
alias2resolvedCommandName,
listOfFormatData
);
ScriptBlock script = this.Context.Engine.ParseScriptBlock(copyItemScript, false);
script.Invoke(new object[] { tempDirectory, directory });
this.DisplayDirectory(new List<string> { directory.FullName });
}
#endregion Methods
}
/// <summary>
/// This class implements Import-PSSession cmdlet.
/// Spec: http://cmdletdesigner/SpecViewer/Default.aspx?Project=PowerShell&Cmdlet=Import-Command .
/// </summary>
[Cmdlet(VerbsData.Import, "PSSession", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096712")]
[OutputType(typeof(PSModuleInfo))]
public sealed class ImportPSSessionCommand : ImplicitRemotingCommandBase
{
#region Hooking runspace closed event into module cleanup
private const string runspaceStateChangedScript = @"& {
if ('Closed' -eq $eventArgs.RunspaceStateInfo.State)
{
$sourceIdentifier = [system.management.automation.wildcardpattern]::Escape($eventSubscriber.SourceIdentifier)
Unregister-Event -SourceIdentifier $sourceIdentifier -Force -ErrorAction SilentlyContinue
$moduleInfo = $event.MessageData
Remove-Module -ModuleInfo $moduleInfo -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath $moduleInfo.ModuleBase -Recurse -Force -ErrorAction SilentlyContinue
$moduleInfo = $null
}
}
";
private const string unregisterEventCleanUpScript = @"
$sourceIdentifier = [system.management.automation.wildcardpattern]::Escape($eventSubscriber.SourceIdentifier)
Unregister-Event -SourceIdentifier $sourceIdentifier -Force -ErrorAction SilentlyContinue
if ($null -ne $previousScript)
{
& $previousScript $args
}
";
private void RegisterModuleCleanUp(PSModuleInfo moduleInfo)
{
if (moduleInfo == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(moduleInfo));
}
// Note: we are using this.Context.Events to make sure that the event handler
// is executing on the pipeline thread (for thread-safety)
string sourceIdentifier = StringUtil.Format(ImplicitRemotingStrings.EventSourceIdentifier, this.Session.InstanceId, this.ModuleGuid);
PSEventSubscriber eventSubscriber = this.Context.Events.SubscribeEvent(
this.Session.Runspace,
"StateChanged",
sourceIdentifier,
PSObject.AsPSObject(moduleInfo),
this.Context.Engine.ParseScriptBlock(runspaceStateChangedScript, false),
true, false);
//
// hook into moduleInfo.OnRemove to remove the handler when the module goes away
//
ScriptBlock newScript = this.Context.Engine.ParseScriptBlock(unregisterEventCleanUpScript, false);
newScript = newScript.GetNewClosure(); // create a separate scope for variables set below
newScript.Module.SessionState.PSVariable.Set("eventSubscriber", eventSubscriber);
newScript.Module.SessionState.PSVariable.Set("previousScript", moduleInfo.OnRemove);
moduleInfo.OnRemove = newScript;
}
#endregion
#region Creating and importing the module
private const string importModuleScript = @"
param($name, $session, $prefix, $disableNameChecking)
Import-Module -Name $name -Alias * -Function * -Prefix $prefix -DisableNameChecking:$disableNameChecking -PassThru -ArgumentList @($session)
";
private PSModuleInfo CreateModule(string manifestFile)
{
ScriptBlock script = this.Context.Engine.ParseScriptBlock(importModuleScript, false);
Collection<PSObject> results = script.Invoke(manifestFile, this.Session, this.Prefix, _disableNameChecking);
Dbg.Assert(results != null, "Import-Module should always succeed");
Dbg.Assert(results.Count == 1, "Import-Module should always succeed");
Dbg.Assert(results[0].BaseObject is PSModuleInfo, "Import-Module should always succeed");
return (PSModuleInfo)(results[0].BaseObject);
}
#endregion
#region Extra parameters
/// <summary>
/// This parameter specified a prefix used to modify names of imported commands.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public new string Prefix
{
get { return base.Prefix; }
set { base.Prefix = value; }
}
/// <summary>
/// Disable warnings on cmdlet and function names that have non-standard verbs
/// or non-standard characters in the noun.
/// Also disable security related checks against command and parameter names.
/// </summary>
[Parameter]
public SwitchParameter DisableNameChecking
{
get { return _disableNameChecking; }
set { _disableNameChecking = value; }
}
private bool _disableNameChecking;
#endregion
/// <summary>
/// Performs initialization of cmdlet execution.
/// </summary>
protected override void BeginProcessing()
{
// Module and FullyQualifiedModule should not be specified at the same time.
// Throw out terminating error if this is the case.
if (IsModuleSpecified && IsFullyQualifiedModuleSpecified)
{
string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, nameof(Module), nameof(FullyQualifiedModule));
ErrorRecord error = new(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null);
ThrowTerminatingError(error);
}
DirectoryInfo moduleDirectory = PathUtils.CreateTemporaryDirectory();
Dictionary<string, string> alias2resolvedCommandName;
List<CommandMetadata> listOfCommandMetadata = this.GetRemoteCommandMetadata(out alias2resolvedCommandName);
List<ExtendedTypeDefinition> listOfFormatData = this.GetRemoteFormatData();
List<string> generatedFiles = this.GenerateProxyModule(
moduleDirectory,
Path.GetFileName(moduleDirectory.FullName),
Encoding.Unicode,
false,
listOfCommandMetadata,
alias2resolvedCommandName,
listOfFormatData);
string manifestFile = null;
foreach (string file in generatedFiles)
{
if (Path.GetExtension(file).Equals(".psd1", StringComparison.OrdinalIgnoreCase))
{
manifestFile = file;
}
}
Dbg.Assert(manifestFile != null, "A psd1 file should always be generated");
PSModuleInfo moduleInfo = this.CreateModule(manifestFile);
this.RegisterModuleCleanUp(moduleInfo);
this.WriteObject(moduleInfo);
}
}
/// <summary>
/// Base class for implicit remoting cmdlets.
/// </summary>
public class ImplicitRemotingCommandBase : PSCmdlet
{
internal const string ImplicitRemotingKey = "ImplicitRemoting";
internal const string ImplicitRemotingHashKey = "Hash";
internal const string ImplicitRemotingCommandsToSkipKey = "CommandsToSkip";
#region Constructor
internal ImplicitRemotingCommandBase()
{
this.CommandName = new string[] { "*" };
_commandParameterSpecified = false;
this.FormatTypeName = new string[] { "*" };
_formatTypeNamesSpecified = false;
}
#endregion
#region Common cmdlet parameters
#region related to Get-Command
/// <summary>
/// Gets or sets the path(s) or name(s) of the commands to retrieve.
/// </summary>
[Parameter(Position = 2)]
[Alias("Name")]
public string[] CommandName
{
get
{
return _commandNameParameter;
}
set
{
_commandNameParameter = value;
_commandParameterSpecified = true;
_commandNamePatterns = SessionStateUtilities.CreateWildcardsFromStrings(
_commandNameParameter,
WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
}
}
private string[] _commandNameParameter;
private Collection<WildcardPattern> _commandNamePatterns; // initialized to default value in the constructor
/// <summary>
/// Allows shadowing and/or overwriting of existing local/client commands.
/// </summary>
[Parameter]
public SwitchParameter AllowClobber { get; set; } = new SwitchParameter(false);
/// <summary>
/// The parameter that all additional arguments get bound to. These arguments are used
/// when retrieving dynamic parameters from cmdlets that support them.
/// </summary>
[Parameter]
[AllowNull]
[AllowEmptyCollection]
[Alias("Args")]
public object[] ArgumentList
{
get
{
return _commandArgs;
}
set
{
_commandArgs = value;
_commandParameterSpecified = true;
}
}
private object[] _commandArgs;
/// <summary>
/// Gets or sets the type of the command to get.
/// </summary>
[Parameter]
[Alias("Type")]
public CommandTypes CommandType
{
get
{
return _commandType;
}
set
{
_commandType = value;
_commandParameterSpecified = true;
}
}
private CommandTypes _commandType = CommandTypes.All & (~(CommandTypes.Application | CommandTypes.Script | CommandTypes.ExternalScript));
/// <summary>
/// Gets or sets the PSSnapin parameter to the cmdlet.
/// </summary>
[Parameter]
[Alias("PSSnapin")]
[ValidateNotNull]
public string[] Module
{
get
{
return _PSSnapins;
}
set
{
if (value == null)
{
value = Array.Empty<string>();
}
_PSSnapins = value;
_commandParameterSpecified = true;
IsModuleSpecified = true;
}
}
private string[] _PSSnapins = Array.Empty<string>();
internal bool IsModuleSpecified = false;
/// <summary>
/// Gets or sets the FullyQualifiedModule parameter to the cmdlet.
/// </summary>
[Parameter]
[ValidateNotNull]
public ModuleSpecification[] FullyQualifiedModule
{
get
{
return _moduleSpecifications;
}
set
{
if (value != null)
{
_moduleSpecifications = value;
}
_commandParameterSpecified = true;
IsFullyQualifiedModuleSpecified = true;
}
}
private ModuleSpecification[] _moduleSpecifications = Array.Empty<ModuleSpecification>();
internal bool IsFullyQualifiedModuleSpecified = false;
private bool _commandParameterSpecified; // initialized to default value in the constructor
#endregion related to Get-Command
#region related to F&O
/// <summary>
/// Gets or sets the types for which we should get formatting and output data.
/// </summary>
[Parameter(Position = 3)]
public string[] FormatTypeName
{
get
{
return _formatTypeNameParameter;
}
set
{
_formatTypeNameParameter = value;
_formatTypeNamesSpecified = true;
_formatTypeNamePatterns = SessionStateUtilities.CreateWildcardsFromStrings(
_formatTypeNameParameter,
WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
}
}
private string[] _formatTypeNameParameter; // initialized to default value in the constructor
private Collection<WildcardPattern> _formatTypeNamePatterns;
private bool _formatTypeNamesSpecified; // initialized to default value in the constructor
#endregion
#region Related to modules
/// <summary>
/// This parameter specified a prefix used to modify names of imported commands.
/// </summary>
internal string Prefix { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the certificate with which to sign the format file and psm1 file.
/// </summary>
[Parameter]
public X509Certificate2 Certificate { get; set; }
#endregion
/// <summary>
/// The PSSession object describing the remote runspace
/// using which the specified cmdlet operation will be performed.
/// </summary>
[Parameter(Mandatory = true, Position = 0)]
[ValidateNotNull]
public PSSession Session { get; set; }
#endregion Parameters
#region Localized errors and messages
internal ErrorDetails GetErrorDetails(string errorId, params object[] args)
{
if (string.IsNullOrEmpty(errorId))
{
throw PSTraceSource.NewArgumentNullException(nameof(errorId));
}
return new ErrorDetails(
typeof(ImplicitRemotingCommandBase).GetTypeInfo().Assembly,
"Microsoft.PowerShell.Commands.Utility.resources.ImplicitRemotingStrings",
errorId,
args);
}
private ErrorRecord GetErrorNoCommandsImportedBecauseOfSkipping()
{
const string errorId = "ErrorNoCommandsImportedBecauseOfSkipping";
ErrorDetails details = this.GetErrorDetails(errorId);
ErrorRecord errorRecord = new(
new ArgumentException(details.Message),
errorId,
ErrorCategory.InvalidResult,
null);
errorRecord.ErrorDetails = details;
return errorRecord;
}
private ErrorRecord GetErrorMalformedDataFromRemoteCommand(string commandName)
{
if (string.IsNullOrEmpty(commandName))
{
throw PSTraceSource.NewArgumentNullException(nameof(commandName));
}
const string errorId = "ErrorMalformedDataFromRemoteCommand";
ErrorDetails details = this.GetErrorDetails(errorId, commandName);
ErrorRecord errorRecord = new(
new ArgumentException(details.Message),
errorId,
ErrorCategory.InvalidResult,
null);
errorRecord.ErrorDetails = details;
return errorRecord;
}
private ErrorRecord GetErrorCommandSkippedBecauseOfShadowing(string commandNames)
{
if (string.IsNullOrEmpty(commandNames))
{
throw PSTraceSource.NewArgumentNullException(nameof(commandNames));
}
const string errorId = "ErrorCommandSkippedBecauseOfShadowing";
ErrorDetails details = this.GetErrorDetails(errorId, commandNames);
ErrorRecord errorRecord = new(
new InvalidOperationException(details.Message),
errorId,
ErrorCategory.InvalidData,
null);
errorRecord.ErrorDetails = details;
return errorRecord;
}
private ErrorRecord GetErrorSkippedNonRequestedCommand(string commandName)
{
if (string.IsNullOrEmpty(commandName))
{
throw PSTraceSource.NewArgumentNullException(nameof(commandName));
}
const string errorId = "ErrorSkippedNonRequestedCommand";
ErrorDetails details = this.GetErrorDetails(errorId, commandName);
ErrorRecord errorRecord = new(
new InvalidOperationException(details.Message),
errorId,
ErrorCategory.ResourceExists,
null);
errorRecord.ErrorDetails = details;
return errorRecord;
}
private ErrorRecord GetErrorSkippedNonRequestedTypeDefinition(string typeName)
{
if (string.IsNullOrEmpty(typeName))
{
throw PSTraceSource.NewArgumentNullException(nameof(typeName));
}
const string errorId = "ErrorSkippedNonRequestedTypeDefinition";
ErrorDetails details = this.GetErrorDetails(errorId, typeName);
ErrorRecord errorRecord = new(
new InvalidOperationException(details.Message),
errorId,
ErrorCategory.ResourceExists,
null);
errorRecord.ErrorDetails = details;
return errorRecord;
}
private ErrorRecord GetErrorSkippedUnsafeCommandName(string commandName)
{
if (string.IsNullOrEmpty(commandName))
{
throw PSTraceSource.NewArgumentNullException(nameof(commandName));
}
const string errorId = "ErrorSkippedUnsafeCommandName";
ErrorDetails details = this.GetErrorDetails(errorId, commandName);
ErrorRecord errorRecord = new(
new InvalidOperationException(details.Message),
errorId,
ErrorCategory.InvalidData,
null);
errorRecord.ErrorDetails = details;
return errorRecord;
}
private ErrorRecord GetErrorSkippedUnsafeNameInMetadata(string commandName, string nameType, string name)
{
if (string.IsNullOrEmpty(commandName))
{
throw PSTraceSource.NewArgumentNullException(nameof(commandName));
}
if (string.IsNullOrEmpty(nameType))
{
throw PSTraceSource.NewArgumentNullException(nameof(nameType));
}
Dbg.Assert(nameType.Equals("Alias") || nameType.Equals("ParameterSet") || nameType.Equals("Parameter"), "nameType matches resource names");
if (string.IsNullOrEmpty(name))
{
throw PSTraceSource.NewArgumentNullException(nameof(name));
}
string errorId = "ErrorSkippedUnsafe" + nameType + "Name";
ErrorDetails details = this.GetErrorDetails(errorId, commandName, name);
ErrorRecord errorRecord = new(
new InvalidOperationException(details.Message),
errorId,
ErrorCategory.InvalidData,
null);
errorRecord.ErrorDetails = details;
return errorRecord;
}
private ErrorRecord GetErrorFromRemoteCommand(string commandName, RuntimeException runtimeException)
{
if (string.IsNullOrEmpty(commandName))
{
throw PSTraceSource.NewArgumentNullException(nameof(commandName));
}
if (runtimeException == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(runtimeException));
}
string errorId;
ErrorDetails errorDetails;
ErrorRecord errorRecord;
//
// handle recognized types of exceptions first
//
RemoteException remoteException = runtimeException as RemoteException;
if ((remoteException != null) && (remoteException.SerializedRemoteException != null))
{
if (Deserializer.IsInstanceOfType(remoteException.SerializedRemoteException, typeof(CommandNotFoundException)))
{
errorId = "ErrorRequiredRemoteCommandNotFound";
errorDetails = this.GetErrorDetails(errorId, this.MyInvocation.MyCommand.Name);
errorRecord = new ErrorRecord(
new RuntimeException(errorDetails.Message, runtimeException),
errorId,
ErrorCategory.ObjectNotFound,
null);
errorRecord.ErrorDetails = errorDetails;
return errorRecord;
}
}
//
// output a generic error message if exception is not recognized
//
errorId = "ErrorFromRemoteCommand";
errorDetails = this.GetErrorDetails(errorId, commandName, runtimeException.Message);
errorRecord = new ErrorRecord(
new RuntimeException(errorDetails.Message, runtimeException),
errorId,
ErrorCategory.InvalidResult,
null);
errorRecord.ErrorDetails = errorDetails;
return errorRecord;
}
private ErrorRecord GetErrorCouldntResolvedAlias(string aliasName)
{
if (string.IsNullOrEmpty(aliasName))
{
throw PSTraceSource.NewArgumentNullException(nameof(aliasName));
}
const string errorId = "ErrorCouldntResolveAlias";
ErrorDetails details = this.GetErrorDetails(errorId, aliasName);
ErrorRecord errorRecord = new(
new ArgumentException(details.Message),
errorId,
ErrorCategory.OperationTimeout,
null);
errorRecord.ErrorDetails = details;
return errorRecord;
}
private ErrorRecord GetErrorNoResultsFromRemoteEnd(string commandName)
{
if (string.IsNullOrEmpty(commandName))
{
throw PSTraceSource.NewArgumentNullException(nameof(commandName));
}
const string errorId = "ErrorNoResultsFromRemoteEnd";
ErrorDetails details = this.GetErrorDetails(errorId, commandName);
ErrorRecord errorRecord = new(
new ArgumentException(details.Message),
errorId,
ErrorCategory.InvalidResult,
null);
errorRecord.ErrorDetails = details;
return errorRecord;
}
private readonly List<string> _commandsSkippedBecauseOfShadowing = new();
private void ReportSkippedCommands()
{
if (_commandsSkippedBecauseOfShadowing.Count != 0)
{
string skippedCommands = string.Join(", ", _commandsSkippedBecauseOfShadowing.ToArray());
ErrorRecord errorRecord = this.GetErrorCommandSkippedBecauseOfShadowing(skippedCommands);
this.WriteWarning(errorRecord.ErrorDetails.Message);
}
}
#endregion
#region Logic to avoid commands we don't want to shadow
private bool IsCommandNameMatchingParameters(string commandName)
{
if (SessionStateUtilities.MatchesAnyWildcardPattern(commandName, _commandNamePatterns, false))
{
return true;
}
string nameWithoutExtension = Path.GetFileNameWithoutExtension(commandName);
if (!nameWithoutExtension.Equals(commandName, StringComparison.OrdinalIgnoreCase))
{
return SessionStateUtilities.MatchesAnyWildcardPattern(nameWithoutExtension, _commandNamePatterns, false);
}
return false;
}
private Dictionary<string, object> _existingCommands;
private Dictionary<string, object> ExistingCommands
{
get
{
if (_existingCommands == null)
{
_existingCommands = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
CommandSearcher searcher = new(
"*",
SearchResolutionOptions.CommandNameIsPattern | SearchResolutionOptions.ResolveAliasPatterns | SearchResolutionOptions.ResolveFunctionPatterns,
CommandTypes.All,
this.Context);
foreach (CommandInfo commandInfo in searcher)
{
_existingCommands[commandInfo.Name] = null;
}
}
return _existingCommands;
}
}
private bool IsShadowingExistingCommands(string commandName)
{
commandName = ModuleCmdletBase.AddPrefixToCommandName(commandName, this.Prefix);
CommandSearcher searcher = new(commandName, SearchResolutionOptions.None, CommandTypes.All, this.Context);
foreach (string expandedCommandName in searcher.ConstructSearchPatternsFromName(commandName))
{
if (this.ExistingCommands.ContainsKey(expandedCommandName))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns true if command doesn't shadow OR is in the -AllowShadowing parameter.
/// </summary>
/// <param name="commandName"></param>
/// <returns></returns>
private bool IsCommandNameAllowedForImport(string commandName)
{
if (string.IsNullOrEmpty(commandName))
{
throw PSTraceSource.NewArgumentNullException(nameof(commandName));
}
if (this.AllowClobber.IsPresent)
{
return true;
}
if (IsShadowingExistingCommands(commandName))
{
_commandsSkippedBecauseOfShadowing.Add(commandName);
return false;
}
else
{
return true;
}
}
#endregion
#region Logic to skip commands the server doesn't want to import
private List<string> CommandSkipListFromServer
{
get
{
// try to get the list from server's application private data
if (_commandSkipListFromServer == null)
{
string[] serverDeclaredListOfCommandsToSkip;
if (PSPrimitiveDictionary.TryPathGet(
this.Session.ApplicationPrivateData,
out serverDeclaredListOfCommandsToSkip,
ImplicitRemotingKey,
ImplicitRemotingCommandsToSkipKey))
{
_commandSkipListFromServer = new List<string>();
if (serverDeclaredListOfCommandsToSkip != null)
{
_commandSkipListFromServer.AddRange(serverDeclaredListOfCommandsToSkip);
}
}
}
// fallback to the default list that hardcodes ...
if (_commandSkipListFromServer == null)
{
_commandSkipListFromServer = new List<string>();
// ... A) 5 commands used (some required some not) by implicit remoting
_commandSkipListFromServer.Add("Get-Command");
_commandSkipListFromServer.Add("Get-FormatData");
_commandSkipListFromServer.Add("Get-Help");
_commandSkipListFromServer.Add("Select-Object");
_commandSkipListFromServer.Add("Measure-Object");
// ... B) 2 commands required for 1:1 remoting
_commandSkipListFromServer.Add("Exit-PSSession");
_commandSkipListFromServer.Add("Out-Default");
}
return _commandSkipListFromServer;
}
}
private List<string> _commandSkipListFromServer;
private bool IsCommandSkippedByServerDeclaration(string commandName)
{
// skipped = commandName is on the CommandSkipListFromServer and is not on the this.CommandName list
foreach (string commandToSkip in this.CommandSkipListFromServer)
{
if (commandToSkip.Equals(commandName, StringComparison.OrdinalIgnoreCase))
{
if (this.CommandName != null)
{
foreach (string commandNameParameter in this.CommandName)
{
if (commandName.Equals(commandNameParameter, StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
}
return true;
}
}
return false;
}
#endregion
#region Generic rehydration helpers
private T ConvertTo<T>(string commandName, object value)
{
return ConvertTo<T>(commandName, value, false);
}
private T ConvertTo<T>(string commandName, object value, bool nullOk)
{
if (value == null)
{
if (nullOk)
{
return default(T);
}
else