/
CommandMetadata.cs
1566 lines (1340 loc) · 70.5 KB
/
CommandMetadata.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.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Reflection;
using System.Text;
using Microsoft.PowerShell.Commands;
using Dbg = System.Diagnostics.Debug;
using System.Diagnostics.CodeAnalysis;
namespace System.Management.Automation
{
/// <summary>
/// Defines session capabilities provided by a PowerShell session.
/// </summary>
/// <seealso cref="System.Management.Automation.Runspaces.InitialSessionState.CreateRestricted"/>
/// <seealso cref="System.Management.Automation.CommandMetadata.GetRestrictedCommands"/>
[Flags]
public enum SessionCapabilities
{
/// <summary>
/// Session with <see cref="RemoteServer"/> capabilities can be made available on a server
/// that wants to provide a full user experience to PowerShell clients.
/// Clients connecting to the server will be able to use implicit remoting
/// (Import-PSSession, Export-PSSession) as well as interactive remoting (Enter-PSSession, Exit-PSSession).
/// </summary>
RemoteServer = 0x1,
/// <summary>
/// Include language capabilities.
/// </summary>
Language = 0x4
}
/// <summary>
/// This class represents the compiled metadata for a command type.
/// </summary>
[DebuggerDisplay("CommandName = {Name}; Type = {CommandType}")]
public sealed class CommandMetadata
{
#region Public Constructor
/// <summary>
/// Constructs a CommandMetadata object for the given CLS complaint type
/// <paramref name="commandType"/>.
/// </summary>
/// <param name="commandType">
/// CLS complaint type to inspect for Cmdlet metadata.
/// </param>
/// <exception cref="ArgumentNullException">
/// commandType is null.
/// </exception>
/// <exception cref="MetadataException">
/// If a parameter defines the same parameter-set name multiple times.
/// If the attributes could not be read from a property or field.
/// </exception>
public CommandMetadata(Type commandType)
{
Init(null, null, commandType, false);
}
/// <summary>
/// Construct a CommandMetadata object for the given commandInfo.
/// </summary>
/// <param name="commandInfo">
/// The commandInfo object to construct CommandMetadata for
/// </param>
/// <exception cref="ArgumentNullException">
/// commandInfo is null.
/// </exception>
/// <exception cref="PSNotSupportedException">
/// If the commandInfo is an alias to an unknown command, or if the commandInfo
/// is an unsupported command type.
/// </exception>
public CommandMetadata(CommandInfo commandInfo)
: this(commandInfo, false)
{
}
/// <summary>
/// Construct a CommandMetadata object for the given commandInfo.
/// </summary>
/// <param name="commandInfo">
/// The commandInfo object to construct CommandMetadata for
/// </param>
/// <param name="shouldGenerateCommonParameters">
/// Should common parameters be included in the metadata?
/// </param>
/// <exception cref="ArgumentNullException">
/// commandInfo is null.
/// </exception>
/// <exception cref="PSNotSupportedException">
/// If the commandInfo is an alias to an unknown command, or if the commandInfo
/// is an unsupported command type.
/// </exception>
public CommandMetadata(CommandInfo commandInfo, bool shouldGenerateCommonParameters)
{
if (commandInfo == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(commandInfo));
}
while (commandInfo is AliasInfo)
{
commandInfo = ((AliasInfo)commandInfo).ResolvedCommand;
if (commandInfo == null)
{
throw PSTraceSource.NewNotSupportedException();
}
}
CmdletInfo cmdletInfo;
ExternalScriptInfo scriptInfo;
FunctionInfo funcInfo;
if ((cmdletInfo = commandInfo as CmdletInfo) != null)
{
Init(commandInfo.Name, cmdletInfo.FullName, cmdletInfo.ImplementingType, shouldGenerateCommonParameters);
}
else if ((scriptInfo = commandInfo as ExternalScriptInfo) != null)
{
// Accessing the script block property here reads and parses the script
Init(scriptInfo.ScriptBlock, scriptInfo.Path, shouldGenerateCommonParameters);
_wrappedCommandType = CommandTypes.ExternalScript;
}
else if ((funcInfo = commandInfo as FunctionInfo) != null)
{
Init(funcInfo.ScriptBlock, funcInfo.Name, shouldGenerateCommonParameters);
_wrappedCommandType = commandInfo.CommandType;
}
else
{
throw PSTraceSource.NewNotSupportedException();
}
}
/// <summary>
/// Construct a CommandMetadata object for a script file.
/// </summary>
/// <param name="path">The path to the script file.</param>
public CommandMetadata(string path)
{
string scriptName = IO.Path.GetFileName(path);
ExternalScriptInfo scriptInfo = new ExternalScriptInfo(scriptName, path);
Init(scriptInfo.ScriptBlock, path, false);
_wrappedCommandType = CommandTypes.ExternalScript;
}
/// <summary>
/// A copy constructor that creates a deep copy of the <paramref name="other"/> CommandMetadata object.
/// Instances of Attribute and Type classes are copied by reference.
/// </summary>
/// <param name="other">Object to copy.</param>
public CommandMetadata(CommandMetadata other)
{
if (other == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(other));
}
Name = other.Name;
ConfirmImpact = other.ConfirmImpact;
_defaultParameterSetFlag = other._defaultParameterSetFlag;
_defaultParameterSetName = other._defaultParameterSetName;
_implementsDynamicParameters = other._implementsDynamicParameters;
SupportsShouldProcess = other.SupportsShouldProcess;
SupportsPaging = other.SupportsPaging;
SupportsTransactions = other.SupportsTransactions;
this.CommandType = other.CommandType;
_wrappedAnyCmdlet = other._wrappedAnyCmdlet;
_wrappedCommand = other._wrappedCommand;
_wrappedCommandType = other._wrappedCommandType;
_parameters = new Dictionary<string, ParameterMetadata>(other.Parameters.Count, StringComparer.OrdinalIgnoreCase);
// deep copy
foreach (KeyValuePair<string, ParameterMetadata> entry in other.Parameters)
{
_parameters.Add(entry.Key, new ParameterMetadata(entry.Value));
}
// deep copy of the collection, collection items (Attributes) copied by reference
if (other._otherAttributes == null)
{
_otherAttributes = null;
}
else
{
_otherAttributes = new Collection<Attribute>(new List<Attribute>(other._otherAttributes.Count));
foreach (Attribute attribute in other._otherAttributes)
{
_otherAttributes.Add(attribute);
}
}
// not copying those fields/members as they are untouched (and left set to null)
// by public constructors, so we can't rely on those fields/members to be set
// when CommandMetadata comes from a user
_staticCommandParameterMetadata = null;
}
/// <summary>
/// Constructor used by implicit remoting.
/// </summary>
internal CommandMetadata(
string name,
CommandTypes commandType,
bool isProxyForCmdlet,
string defaultParameterSetName,
bool supportsShouldProcess,
ConfirmImpact confirmImpact,
bool supportsPaging,
bool supportsTransactions,
bool positionalBinding,
Dictionary<string, ParameterMetadata> parameters)
{
Name = _wrappedCommand = name;
_wrappedCommandType = commandType;
_wrappedAnyCmdlet = isProxyForCmdlet;
_defaultParameterSetName = defaultParameterSetName;
SupportsShouldProcess = supportsShouldProcess;
SupportsPaging = supportsPaging;
ConfirmImpact = confirmImpact;
SupportsTransactions = supportsTransactions;
PositionalBinding = positionalBinding;
this.Parameters = parameters;
}
private void Init(string name, string fullyQualifiedName, Type commandType, bool shouldGenerateCommonParameters)
{
Name = name;
this.CommandType = commandType;
if (commandType != null)
{
ConstructCmdletMetadataUsingReflection();
_shouldGenerateCommonParameters = shouldGenerateCommonParameters;
}
// Use fully qualified name if available.
_wrappedCommand = !string.IsNullOrEmpty(fullyQualifiedName) ? fullyQualifiedName : Name;
_wrappedCommandType = CommandTypes.Cmdlet;
_wrappedAnyCmdlet = true;
}
private void Init(ScriptBlock scriptBlock, string name, bool shouldGenerateCommonParameters)
{
if (scriptBlock.UsesCmdletBinding)
{
_wrappedAnyCmdlet = true;
}
else
{
// Ignore what was passed in, there are no common parameters if cmdlet binding is not used.
shouldGenerateCommonParameters = false;
}
CmdletBindingAttribute cmdletBindingAttribute = scriptBlock.CmdletBindingAttribute;
if (cmdletBindingAttribute != null)
{
ProcessCmdletAttribute(cmdletBindingAttribute);
}
else if (scriptBlock.UsesCmdletBinding)
{
_defaultParameterSetName = null;
}
Obsolete = scriptBlock.ObsoleteAttribute;
_scriptBlock = scriptBlock;
_wrappedCommand = Name = name;
_shouldGenerateCommonParameters = shouldGenerateCommonParameters;
}
#endregion
#region ctor
/// <summary>
/// Gets the metadata for the specified cmdlet from the cache or creates
/// a new instance if its not in the cache.
/// </summary>
/// <param name="commandName">
/// The name of the command that this metadata represents.
/// </param>
/// <param name="cmdletType">
/// The cmdlet to get the metadata for.
/// </param>
/// <param name="context">
/// The current engine context.
/// </param>
/// <returns>
/// The CommandMetadata for the specified cmdlet.
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="commandName"/> is null or empty.
/// </exception>
/// <exception cref="ArgumentNullException">
/// If <paramref name="cmdletType"/> is null.
/// </exception>
/// <exception cref="ParsingMetadataException">
/// If more than int.MaxValue parameter-sets are defined for the command.
/// </exception>
/// <exception cref="MetadataException">
/// If a parameter defines the same parameter-set name multiple times.
/// If the attributes could not be read from a property or field.
/// </exception>
internal static CommandMetadata Get(string commandName, Type cmdletType, ExecutionContext context)
{
if (string.IsNullOrEmpty(commandName))
{
throw PSTraceSource.NewArgumentException(nameof(commandName));
}
CommandMetadata result = null;
if ((context != null) && (cmdletType != null))
{
string cmdletTypeName = cmdletType.AssemblyQualifiedName;
s_commandMetadataCache.TryGetValue(cmdletTypeName, out result);
}
if (result == null)
{
result = new CommandMetadata(commandName, cmdletType, context);
if ((context != null) && (cmdletType != null))
{
string cmdletTypeName = cmdletType.AssemblyQualifiedName;
s_commandMetadataCache.TryAdd(cmdletTypeName, result);
}
}
return result;
}
/// <summary>
/// Constructs an instance of CommandMetadata using reflection against a bindable object.
/// </summary>
/// <param name="commandName">
/// The name of the command that this metadata represents.
/// </param>
/// <param name="cmdletType">
/// An instance of an object type that can be used to bind MSH parameters. A type is
/// considered bindable if it has at least one field and/or property that is decorated
/// with the ParameterAttribute.
/// </param>
/// <param name="context">
/// The current engine context. If null, the command and type metadata will be generated
/// and will not be cached.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="cmdletType"/> is null.
/// </exception>
/// <exception cref="ParsingMetadataException">
/// If more than int.MaxValue parameter-sets are defined for the command.
/// </exception>
/// <exception cref="MetadataException">
/// If a parameter defines the same parameter-set name multiple times.
/// If the attributes could not be read from a property or field.
/// </exception>
internal CommandMetadata(string commandName, Type cmdletType, ExecutionContext context)
{
if (string.IsNullOrEmpty(commandName))
{
throw PSTraceSource.NewArgumentException(nameof(commandName));
}
Name = commandName;
this.CommandType = cmdletType;
if (cmdletType != null)
{
InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(cmdletType, context, false);
ConstructCmdletMetadataUsingReflection();
_staticCommandParameterMetadata = MergeParameterMetadata(context, parameterMetadata, true);
_defaultParameterSetFlag = _staticCommandParameterMetadata.GenerateParameterSetMappingFromMetadata(_defaultParameterSetName);
_staticCommandParameterMetadata.MakeReadOnly();
}
}
/// <summary>
/// Constructor for creating command metadata from a script block.
/// </summary>
/// <param name="scriptblock"></param>
/// <param name="context"></param>
/// <param name="commandName"></param>
/// <remarks>
/// Unlike cmdlet based on a C# type where cmdlet metadata and parameter
/// metadata is created through reflecting the implementation type, script
/// cmdlet has different way for constructing metadata.
///
/// 1. Metadata for cmdlet itself comes from cmdlet statement, which
/// is parsed into CmdletDeclarationNode and then converted into
/// a CmdletAttribute object.
/// 2. Metadata for parameter comes from parameter declaration statement,
/// which is parsed into parameter nodes with parameter annotations.
/// Information in ParameterNodes is eventually transformed into a
/// dictionary of RuntimeDefinedParameters.
///
/// By the time this constructor is called, information about CmdletAttribute
/// and RuntimeDefinedParameters for the script block has been setup with
/// the scriptblock object.
/// </remarks>
internal CommandMetadata(ScriptBlock scriptblock, string commandName, ExecutionContext context)
{
if (scriptblock == null)
{
throw PSTraceSource.NewArgumentException(nameof(scriptblock));
}
CmdletBindingAttribute cmdletBindingAttribute = scriptblock.CmdletBindingAttribute;
if (cmdletBindingAttribute != null)
{
ProcessCmdletAttribute(cmdletBindingAttribute);
}
else
{
_defaultParameterSetName = null;
}
Obsolete = scriptblock.ObsoleteAttribute;
Name = commandName;
this.CommandType = typeof(PSScriptCmdlet);
if (scriptblock.HasDynamicParameters)
{
_implementsDynamicParameters = true;
}
InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(scriptblock.RuntimeDefinedParameters, false,
scriptblock.UsesCmdletBinding);
_staticCommandParameterMetadata = MergeParameterMetadata(context, parameterMetadata, scriptblock.UsesCmdletBinding);
_defaultParameterSetFlag = _staticCommandParameterMetadata.GenerateParameterSetMappingFromMetadata(_defaultParameterSetName);
_staticCommandParameterMetadata.MakeReadOnly();
}
#endregion ctor
#region Public Properties
/// <summary>
/// Gets the name of the command this metadata represents.
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// The Type which this CommandMetadata represents.
/// </summary>
public Type CommandType { get; private set; }
// The ScriptBlock which this CommandMetadata represents.
private ScriptBlock _scriptBlock;
/// <summary>
/// Gets/Sets the default parameter set name.
/// </summary>
public string DefaultParameterSetName
{
get
{
return _defaultParameterSetName;
}
set
{
if (string.IsNullOrEmpty(value))
{
value = ParameterAttribute.AllParameterSets;
}
_defaultParameterSetName = value;
}
}
private string _defaultParameterSetName = ParameterAttribute.AllParameterSets;
/// <summary>
/// True if the cmdlet declared that it supports ShouldProcess, false otherwise.
/// </summary>
/// <value></value>
public bool SupportsShouldProcess { get; set; }
/// <summary>
/// True if the cmdlet declared that it supports Paging, false otherwise.
/// </summary>
/// <value></value>
public bool SupportsPaging { get; set; }
/// <summary>
/// When true, the command will auto-generate appropriate parameter metadata to support positional
/// parameters if the script hasn't already specified multiple parameter sets or specified positions
/// explicitly via the <see cref="ParameterAttribute"/>.
/// </summary>
public bool PositionalBinding { get; set; } = true;
/// <summary>
/// True if the cmdlet declared that it supports transactions, false otherwise.
/// </summary>
/// <value></value>
public bool SupportsTransactions { get; set; }
/// <summary>
/// Related link URI for Get-Help -Online.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
public string HelpUri { get; set; } = string.Empty;
/// <summary>
/// The remoting capabilities of this cmdlet, when exposed in a context
/// with ambient remoting.
/// </summary>
public RemotingCapability RemotingCapability
{
get
{
RemotingCapability currentRemotingCapability = _remotingCapability;
if ((currentRemotingCapability == Automation.RemotingCapability.PowerShell) &&
((this.Parameters != null) && this.Parameters.ContainsKey("ComputerName")))
{
_remotingCapability = Automation.RemotingCapability.SupportedByCommand;
}
return _remotingCapability;
}
set
{
_remotingCapability = value;
}
}
private RemotingCapability _remotingCapability = RemotingCapability.PowerShell;
/// <summary>
/// Indicates the "destructiveness" of the command operation and
/// when it should be confirmed. This is only effective when
/// the command calls ShouldProcess, which should only occur when
/// SupportsShouldProcess is specified.
/// </summary>
/// <value></value>
public ConfirmImpact ConfirmImpact { get; set; } = ConfirmImpact.Medium;
/// <summary>
/// Gets the parameter data for this command.
/// </summary>
public Dictionary<string, ParameterMetadata> Parameters
{
get
{
if (_parameters == null)
{
// Return parameters for a script block
if (_scriptBlock != null)
{
InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(_scriptBlock.RuntimeDefinedParameters, false,
_scriptBlock.UsesCmdletBinding);
MergedCommandParameterMetadata mergedCommandParameterMetadata =
MergeParameterMetadata(null, parameterMetadata, _shouldGenerateCommonParameters);
_parameters = ParameterMetadata.GetParameterMetadata(mergedCommandParameterMetadata);
}
else if (this.CommandType != null)
{
// Construct compiled parameter metadata from this
InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(this.CommandType, null, false);
MergedCommandParameterMetadata mergedCommandParameterMetadata =
MergeParameterMetadata(null, parameterMetadata, _shouldGenerateCommonParameters);
// Construct parameter metadata from compiled parameter metadata
// compiled parameter metadata is used for internal purposes. It has lots of information
// which is used by ParameterBinder.
_parameters = ParameterMetadata.GetParameterMetadata(mergedCommandParameterMetadata);
}
}
return _parameters;
}
private set
{
_parameters = value;
}
}
private Dictionary<string, ParameterMetadata> _parameters;
private bool _shouldGenerateCommonParameters;
/// <summary>
/// Gets or sets the obsolete attribute on the command.
/// </summary>
/// <value></value>
internal ObsoleteAttribute Obsolete { get; set; }
#endregion
#region internal members
/// <summary>
/// Gets the merged metadata for the command including cmdlet declared parameters,
/// common parameters, and (optionally) ShouldProcess and Transactions parameters.
/// </summary>
/// <value></value>
internal MergedCommandParameterMetadata StaticCommandParameterMetadata
{
get
{
return _staticCommandParameterMetadata;
}
}
private readonly MergedCommandParameterMetadata _staticCommandParameterMetadata;
/// <summary>
/// True if the cmdlet implements dynamic parameters, or false otherwise.
/// </summary>
/// <value></value>
internal bool ImplementsDynamicParameters
{
get { return _implementsDynamicParameters; }
}
private bool _implementsDynamicParameters;
/// <summary>
/// Gets the bit in the parameter set map for the default parameter set.
/// </summary>
internal uint DefaultParameterSetFlag
{
get { return _defaultParameterSetFlag; }
set { _defaultParameterSetFlag = value; }
}
private uint _defaultParameterSetFlag;
/// <summary>
/// A collection of attributes that were declared at the cmdlet level but were not
/// recognized by the engine.
/// </summary>
private readonly Collection<Attribute> _otherAttributes = new Collection<Attribute>();
// command this CommandMetadata instance is intended to wrap
private string _wrappedCommand;
// the type of command this CommandMetadata instance is intended to wrap
private CommandTypes _wrappedCommandType;
// The CommandType for a script cmdlet is not CommandTypes.Cmdlet, yet
// proxy generation needs to know the difference between script and script cmdlet.
private bool _wrappedAnyCmdlet;
internal bool WrappedAnyCmdlet
{
get { return _wrappedAnyCmdlet; }
}
internal CommandTypes WrappedCommandType
{
get
{
return _wrappedCommandType;
}
}
#endregion internal members
#region helper methods
/// <summary>
/// Constructs the command metadata by using reflection against the
/// CLR type.
/// </summary>
/// <exception cref="ParsingMetadataException">
/// If more than int.MaxValue parameter-sets are defined for the command.
/// </exception>
private void ConstructCmdletMetadataUsingReflection()
{
Diagnostics.Assert(
CommandType != null,
"This method should only be called when constructed with the Type");
// Determine if the cmdlet implements dynamic parameters by looking for the interface
Type dynamicParametersType = CommandType.GetInterface(nameof(IDynamicParameters), true);
if (dynamicParametersType != null)
{
_implementsDynamicParameters = true;
}
// Process the attributes on the cmdlet
var customAttributes = CommandType.GetCustomAttributes(false);
foreach (Attribute attribute in customAttributes)
{
CmdletAttribute cmdletAttribute = attribute as CmdletAttribute;
if (cmdletAttribute != null)
{
ProcessCmdletAttribute(cmdletAttribute);
this.Name = cmdletAttribute.VerbName + "-" + cmdletAttribute.NounName;
}
else if (attribute is ObsoleteAttribute)
{
Obsolete = (ObsoleteAttribute)attribute;
}
else
{
_otherAttributes.Add(attribute);
}
}
}
/// <summary>
/// Extracts the cmdlet data from the CmdletAttribute.
/// </summary>
/// <param name="attribute">
/// The CmdletAttribute to process
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="attribute"/> is null.
/// </exception>
/// <exception cref="ParsingMetadataException">
/// If more than int.MaxValue parameter-sets are defined for the command.
/// </exception>
private void ProcessCmdletAttribute(CmdletCommonMetadataAttribute attribute)
{
if (attribute == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(attribute));
}
// Process the default parameter set name
_defaultParameterSetName = attribute.DefaultParameterSetName;
// Check to see if the cmdlet supports ShouldProcess
SupportsShouldProcess = attribute.SupportsShouldProcess;
// Determine the cmdlet's impact confirmation
ConfirmImpact = attribute.ConfirmImpact;
// Check to see if the cmdlet supports paging
SupportsPaging = attribute.SupportsPaging;
// Check to see if the cmdlet supports transactions
SupportsTransactions = attribute.SupportsTransactions;
// Grab related link
HelpUri = attribute.HelpUri;
// Remoting support
_remotingCapability = attribute.RemotingCapability;
// Check to see if the cmdlet uses positional binding
var cmdletBindingAttribute = attribute as CmdletBindingAttribute;
if (cmdletBindingAttribute != null)
{
PositionalBinding = cmdletBindingAttribute.PositionalBinding;
}
}
/// <summary>
/// Merges parameter metadata from different sources: those that are coming from Type,
/// CommonParameters, should process etc.
/// </summary>
/// <param name="context"></param>
/// <param name="parameterMetadata"></param>
/// <param name="shouldGenerateCommonParameters">
/// true if metadata info about Verbose,Debug etc needs to be generated.
/// false otherwise.
/// </param>
private MergedCommandParameterMetadata MergeParameterMetadata(ExecutionContext context, InternalParameterMetadata parameterMetadata, bool shouldGenerateCommonParameters)
{
// Create an instance of the static metadata class
MergedCommandParameterMetadata staticCommandParameterMetadata =
new MergedCommandParameterMetadata();
// First add the metadata for the formal cmdlet parameters
staticCommandParameterMetadata.AddMetadataForBinder(
parameterMetadata,
ParameterBinderAssociation.DeclaredFormalParameters);
// Now add the common parameters metadata
if (shouldGenerateCommonParameters)
{
InternalParameterMetadata commonParametersMetadata =
InternalParameterMetadata.Get(typeof(CommonParameters), context, false);
staticCommandParameterMetadata.AddMetadataForBinder(
commonParametersMetadata,
ParameterBinderAssociation.CommonParameters);
// If the command supports ShouldProcess, add the metadata for
// those parameters
if (this.SupportsShouldProcess)
{
InternalParameterMetadata shouldProcessParametersMetadata =
InternalParameterMetadata.Get(typeof(ShouldProcessParameters), context, false);
staticCommandParameterMetadata.AddMetadataForBinder(
shouldProcessParametersMetadata,
ParameterBinderAssociation.ShouldProcessParameters);
}
// If the command supports paging, add the metadata for
// those parameters
if (this.SupportsPaging)
{
InternalParameterMetadata pagingParametersMetadata =
InternalParameterMetadata.Get(typeof(PagingParameters), context, false);
staticCommandParameterMetadata.AddMetadataForBinder(
pagingParametersMetadata,
ParameterBinderAssociation.PagingParameters);
}
// If the command supports transactions, add the metadata for
// those parameters
if (this.SupportsTransactions)
{
InternalParameterMetadata transactionParametersMetadata =
InternalParameterMetadata.Get(typeof(TransactionParameters), context, false);
staticCommandParameterMetadata.AddMetadataForBinder(
transactionParametersMetadata,
ParameterBinderAssociation.TransactionParameters);
}
}
return staticCommandParameterMetadata;
}
#endregion helper methods
#region Proxy Command generation
/// <summary>
/// Gets the ScriptCmdlet in string format.
/// </summary>
/// <returns></returns>
internal string GetProxyCommand(string helpComment, bool generateDynamicParameters)
{
if (string.IsNullOrEmpty(helpComment))
{
helpComment = string.Format(CultureInfo.InvariantCulture, @"
.ForwardHelpTargetName {0}
.ForwardHelpCategory {1}
",
_wrappedCommand, _wrappedCommandType);
}
string dynamicParamblock = string.Empty;
if (generateDynamicParameters && this.ImplementsDynamicParameters)
{
dynamicParamblock = string.Format(CultureInfo.InvariantCulture, @"
dynamicparam
{{{0}}}
", GetDynamicParamBlock());
}
string result = string.Format(CultureInfo.InvariantCulture, @"{0}
param({1})
{2}begin
{{{3}}}
process
{{{4}}}
end
{{{5}}}
cleanup
{{{6}}}
<#
{7}
#>
",
GetDecl(),
GetParamBlock(),
dynamicParamblock,
GetBeginBlock(),
GetProcessBlock(),
GetEndBlock(),
GetCleanupBlock(),
CodeGeneration.EscapeBlockCommentContent(helpComment));
return result;
}
internal string GetDecl()
{
string result = string.Empty;
string separator = string.Empty;
if (_wrappedAnyCmdlet)
{
StringBuilder decl = new StringBuilder("[CmdletBinding(");
if (!string.IsNullOrEmpty(_defaultParameterSetName))
{
decl.Append(separator);
decl.Append("DefaultParameterSetName='");
decl.Append(CodeGeneration.EscapeSingleQuotedStringContent(_defaultParameterSetName));
decl.Append('\'');
separator = ", ";
}
if (SupportsShouldProcess)
{
decl.Append(separator);
decl.Append("SupportsShouldProcess=$true");
separator = ", ";
decl.Append(separator);
decl.Append("ConfirmImpact='");
decl.Append(ConfirmImpact);
decl.Append('\'');
}
if (SupportsPaging)
{
decl.Append(separator);
decl.Append("SupportsPaging=$true");
separator = ", ";
}
if (SupportsTransactions)
{
decl.Append(separator);
decl.Append("SupportsTransactions=$true");
separator = ", ";
}
if (!PositionalBinding)
{
decl.Append(separator);
decl.Append("PositionalBinding=$false");
separator = ", ";
}
if (!string.IsNullOrEmpty(HelpUri))
{
decl.Append(separator);
decl.Append("HelpUri='");
decl.Append(CodeGeneration.EscapeSingleQuotedStringContent(HelpUri));
decl.Append('\'');
separator = ", ";
}
if (_remotingCapability != RemotingCapability.PowerShell)
{
decl.Append(separator);
decl.Append("RemotingCapability='");
decl.Append(_remotingCapability);
decl.Append('\'');
separator = ", ";
}
decl.Append(")]");
result = decl.ToString();
}
return result;
}
internal string GetParamBlock()
{
if (Parameters.Keys.Count > 0)
{
StringBuilder parameters = new StringBuilder();
string prefix = string.Concat(Environment.NewLine, " ");
string paramDataPrefix = null;
foreach (var pair in Parameters)
{
if (paramDataPrefix != null)
{
parameters.Append(paramDataPrefix);
}
else
{
// syntax for parameter separation : comma followed by new-line.
paramDataPrefix = string.Concat(",", Environment.NewLine);
}
// generate the parameter proxy and append to the list
string paramData = pair.Value.GetProxyParameterData(prefix, pair.Key, _wrappedAnyCmdlet);
parameters.Append(paramData);
}
return parameters.ToString();
}
return string.Empty;
}