forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVar.cs
More file actions
1389 lines (1214 loc) · 44.1 KB
/
Copy pathVar.cs
File metadata and controls
1389 lines (1214 loc) · 44.1 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;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Internal;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Base class for all variable commands.
///
/// Because -Scope is defined in VariableCommandBase, all derived commands
/// must implement -Scope.
/// </summary>
public abstract class VariableCommandBase : PSCmdlet
{
#region Parameters
/// <summary>
/// Selects active scope to work with; used for all variable commands.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string Scope { get; set; }
#endregion parameters
/// <summary>
/// The Include parameter for all the variable commands
/// </summary>
///
protected string[] IncludeFilters
{
get
{
return _include;
}
set
{
if (value == null)
{
value = new string[0];
}
_include = value;
}
}
private string[] _include = new string[0];
/// <summary>
/// The Exclude parameter for all the variable commands
/// </summary>
///
protected string[] ExcludeFilters
{
get
{
return _exclude;
}
set
{
if (value == null)
{
value = new string[0];
}
_exclude = value;
}
}
private string[] _exclude = new string[0];
#region helpers
/// <summary>
/// Gets the matching variable for the specified name, using the
/// Include, Exclude, and Scope parameters defined in the base class.
/// </summary>
///
/// <param name="name">
/// The name or pattern of the variables to retrieve.
/// </param>
///
/// <param name="lookupScope">
/// The scope to do the lookup in. If null or empty the normal scoping
/// rules apply.
/// </param>
///
/// <param name="wasFiltered">
/// True is returned if a variable exists of the given name but was filtered
/// out via globbing, include, or exclude.
/// </param>
///
/// <param name="quiet">
/// If true, don't report errors when trying to access private variables.
/// </param>
///
/// <returns>
/// A collection of the variables matching the name, include, and exclude
/// pattern in the specified scope.
/// </returns>
///
internal List<PSVariable> GetMatchingVariables(string name, string lookupScope, out bool wasFiltered, bool quiet)
{
wasFiltered = false;
List<PSVariable> result = new List<PSVariable>();
if (String.IsNullOrEmpty(name))
{
name = "*";
}
bool nameContainsWildcard = WildcardPattern.ContainsWildcardCharacters(name);
// Now create the filters
WildcardPattern nameFilter =
WildcardPattern.Get(
name,
WildcardOptions.IgnoreCase);
Collection<WildcardPattern> includeFilters =
SessionStateUtilities.CreateWildcardsFromStrings(
_include,
WildcardOptions.IgnoreCase);
Collection<WildcardPattern> excludeFilters =
SessionStateUtilities.CreateWildcardsFromStrings(
_exclude,
WildcardOptions.IgnoreCase);
if (!nameContainsWildcard)
{
// Filter the name here against the include and exclude so that
// we can report if the name was filtered vs. there being no
// variable existing of that name.
bool isIncludeMatch =
SessionStateUtilities.MatchesAnyWildcardPattern(
name,
includeFilters,
true);
bool isExcludeMatch =
SessionStateUtilities.MatchesAnyWildcardPattern(
name,
excludeFilters,
false);
if (!isIncludeMatch || isExcludeMatch)
{
wasFiltered = true;
return result;
}
}
// First get the appropriate view of the variables. If no scope
// is specified, flatten all scopes to produce a currently active
// view.
IDictionary<string, PSVariable> variableTable = null;
if (String.IsNullOrEmpty(lookupScope))
{
variableTable = SessionState.Internal.GetVariableTable();
}
else
{
variableTable = SessionState.Internal.GetVariableTableAtScope(lookupScope);
}
CommandOrigin origin = MyInvocation.CommandOrigin;
foreach (KeyValuePair<string, PSVariable> entry in variableTable)
{
bool isNameMatch = nameFilter.IsMatch(entry.Key);
bool isIncludeMatch =
SessionStateUtilities.MatchesAnyWildcardPattern(
entry.Key,
includeFilters,
true);
bool isExcludeMatch =
SessionStateUtilities.MatchesAnyWildcardPattern(
entry.Key,
excludeFilters,
false);
if (isNameMatch)
{
if (isIncludeMatch && !isExcludeMatch)
{
// See if the variable is visible
if (!SessionState.IsVisible(origin, entry.Value))
{
// In quiet mode, don't report private variable accesses unless they are specific matches...
if (quiet || nameContainsWildcard)
{
wasFiltered = true;
continue;
}
else
{
// Generate an error for elements that aren't visible...
try
{
SessionState.ThrowIfNotVisible(origin, entry.Value);
}
catch (SessionStateException sessionStateException)
{
WriteError(
new ErrorRecord(
sessionStateException.ErrorRecord,
sessionStateException));
// Only report the error once...
wasFiltered = true;
continue;
}
}
}
result.Add(entry.Value);
}
else
{
wasFiltered = true;
}
}
else
{
if (nameContainsWildcard)
{
wasFiltered = true;
}
}
}
return result;
}
#endregion helpers
}
/// <summary>
/// Implements get-variable command.
/// </summary>
[Cmdlet(VerbsCommon.Get, "Variable", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113336")]
[OutputType(typeof(PSVariable))]
public class GetVariableCommand : VariableCommandBase
{
#region parameters
/// <summary>
/// Name of the PSVariable
/// </summary>
[Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty()]
public string[] Name
{
get
{
return _name;
}
set
{
if (value == null)
{
value = new string[] { "*" };
}
_name = value;
}
}
private string[] _name = new string[] { "*" };
/// <summary>
/// Output only the value(s) of the requested variable(s).
/// </summary>
[Parameter]
public SwitchParameter ValueOnly
{
get
{
return _valueOnly;
}
set
{
_valueOnly = value;
}
}
private bool _valueOnly;
/// <summary>
/// The Include parameter for all the variable commands
/// </summary>
///
[Parameter]
public string[] Include
{
get
{
return IncludeFilters;
}
set
{
IncludeFilters = value;
}
}
/// <summary>
/// The Exclude parameter for all the variable commands
/// </summary>
///
[Parameter]
public string[] Exclude
{
get
{
return ExcludeFilters;
}
set
{
ExcludeFilters = value;
}
}
#endregion parameters
/// <summary>
/// Implements ProcessRecord() method for get-variable's command.
/// </summary>
protected override void ProcessRecord()
{
foreach (string varName in _name)
{
bool wasFiltered = false;
List<PSVariable> matchingVariables =
GetMatchingVariables(varName, Scope, out wasFiltered, /*quiet*/ false);
matchingVariables.Sort(
delegate (PSVariable left, PSVariable right)
{
return StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name);
});
bool matchFound = false;
foreach (PSVariable matchingVariable in matchingVariables)
{
matchFound = true;
if (_valueOnly)
{
WriteObject(matchingVariable.Value);
}
else
{
WriteObject(matchingVariable);
}
}
if (!matchFound && !wasFiltered)
{
ItemNotFoundException itemNotFound =
new ItemNotFoundException(
varName,
"VariableNotFound",
SessionStateStrings.VariableNotFound);
WriteError(
new ErrorRecord(
itemNotFound.ErrorRecord,
itemNotFound));
}
}
}
}
/// <summary>
/// Class implementing new-variable command
/// </summary>
[Cmdlet(VerbsCommon.New, "Variable", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113361")]
public sealed class NewVariableCommand : VariableCommandBase
{
#region parameters
/// <summary>
/// Name of the PSVariable
/// </summary>
[Parameter(Position = 0, ValueFromPipelineByPropertyName = true, Mandatory = true)]
public string Name { get; set; }
/// <summary>
/// Value of the PSVariable
/// </summary>
[Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
public object Value { get; set; }
/// <summary>
/// Description of the variable
/// </summary>
[Parameter]
public string Description { get; set; }
/// <summary>
/// The options for the variable to specify if the variable should
/// be ReadOnly, Constant, and/or Private.
/// </summary>
///
[Parameter]
public ScopedItemOptions Option { get; set; } = ScopedItemOptions.None;
/// <summary>
/// Specifies the visibility of the new variable...
/// </summary>
[Parameter]
public SessionStateEntryVisibility Visibility
{
get
{
return (SessionStateEntryVisibility)_visibility;
}
set
{
_visibility = value;
}
}
private SessionStateEntryVisibility? _visibility;
/// <summary>
/// Force the operation to make the best attempt at setting the variable.
/// </summary>
[Parameter]
public SwitchParameter Force
{
get
{
return _force;
}
set
{
_force = value;
}
}
private bool _force;
/// <summary>
/// The variable object should be passed down the pipeline.
/// </summary>
[Parameter]
public SwitchParameter PassThru
{
get
{
return _passThru;
}
set
{
_passThru = value;
}
}
private bool _passThru;
#endregion parameters
/// <summary>
/// Add objects received on the pipeline to an ArrayList of values, to
/// take the place of the Value parameter if none was specified on the
/// command line.
/// </summary>
///
protected override void ProcessRecord()
{
// If Force is not specified, see if the variable already exists
// in the specified scope. If the scope isn't specified, then
// check to see if it exists in the current scope.
if (!Force)
{
PSVariable varFound = null;
if (String.IsNullOrEmpty(Scope))
{
varFound =
SessionState.PSVariable.GetAtScope(Name, "local");
}
else
{
varFound =
SessionState.PSVariable.GetAtScope(Name, Scope);
}
if (varFound != null)
{
SessionStateException sessionStateException =
new SessionStateException(
Name,
SessionStateCategory.Variable,
"VariableAlreadyExists",
SessionStateStrings.VariableAlreadyExists,
ErrorCategory.ResourceExists);
WriteError(
new ErrorRecord(
sessionStateException.ErrorRecord,
sessionStateException));
return;
}
}
// Since the variable doesn't exist or -Force was specified,
// Call should process to validate the set with the user.
string action = VariableCommandStrings.NewVariableAction;
string target = StringUtil.Format(VariableCommandStrings.NewVariableTarget, Name, Value);
if (ShouldProcess(target, action))
{
PSVariable newVariable = new PSVariable(Name, Value, Option);
if (_visibility != null)
{
newVariable.Visibility = (SessionStateEntryVisibility)_visibility;
}
if (Description != null)
{
newVariable.Description = Description;
}
try
{
if (String.IsNullOrEmpty(Scope))
{
SessionState.Internal.NewVariable(newVariable, Force);
}
else
{
SessionState.Internal.NewVariableAtScope(newVariable, Scope, Force);
}
}
catch (SessionStateException sessionStateException)
{
WriteError(
new ErrorRecord(
sessionStateException.ErrorRecord,
sessionStateException));
return;
}
catch (PSArgumentException argException)
{
WriteError(
new ErrorRecord(
argException.ErrorRecord,
argException));
return;
}
if (_passThru)
{
WriteObject(newVariable);
}
}
} // ProcessRecord
} // NewVariableCommand
/// <summary>
/// This class implements set-variable command
/// </summary>
[Cmdlet(VerbsCommon.Set, "Variable", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113401")]
[OutputType(typeof(PSVariable))]
public sealed class SetVariableCommand : VariableCommandBase
{
#region parameters
/// <summary>
/// Name of the PSVariable(s) to set
/// </summary>
[Parameter(Position = 0, ValueFromPipelineByPropertyName = true, Mandatory = true)]
public string[] Name { get; set; }
/// <summary>
/// Value of the PSVariable
/// </summary>
[Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
public object Value { get; set; } = AutomationNull.Value;
/// <summary>
/// The Include parameter for all the variable commands
/// </summary>
///
[Parameter]
public string[] Include
{
get
{
return IncludeFilters;
}
set
{
IncludeFilters = value;
}
}
/// <summary>
/// The Exclude parameter for all the variable commands
/// </summary>
///
[Parameter]
public string[] Exclude
{
get
{
return ExcludeFilters;
}
set
{
ExcludeFilters = value;
}
}
/// <summary>
/// Description of the variable
/// </summary>
[Parameter]
public string Description { get; set; }
/// <summary>
/// The options for the variable to specify if the variable should
/// be ReadOnly, Constant, and/or Private.
/// </summary>
///
[Parameter]
public ScopedItemOptions Option
{
get
{
return (ScopedItemOptions)_options;
}
set
{
_options = value;
}
}
private Nullable<ScopedItemOptions> _options;
/// <summary>
/// Force the operation to make the best attempt at setting the variable.
/// </summary>
[Parameter]
public SwitchParameter Force
{
get
{
return _force;
}
set
{
_force = value;
}
}
private bool _force;
/// <summary>
/// Sets the visibility of the variable...
/// </summary>
[Parameter]
public SessionStateEntryVisibility Visibility
{
get
{
return (SessionStateEntryVisibility)_visibility;
}
set
{
_visibility = value;
}
}
private SessionStateEntryVisibility? _visibility;
/// <summary>
/// The variable object should be passed down the pipeline.
/// </summary>
[Parameter]
public SwitchParameter PassThru
{
get
{
return _passThru;
}
set
{
_passThru = value;
}
}
private bool _passThru;
private bool _nameIsFormalParameter;
private bool _valueIsFormalParameter;
#endregion parameters
/// <summary>
/// Checks to see if the name and value parameters were
/// bound as formal parameters.
/// </summary>
protected override void BeginProcessing()
{
if (Name != null && Name.Length > 0)
{
_nameIsFormalParameter = true;
}
if (Value != AutomationNull.Value)
{
_valueIsFormalParameter = true;
}
}
/// <summary>
/// If name and value are both specified as a formal parameters, then
/// just ignore the incoming objects in ProcessRecord.
/// If name is a formal parameter but the value is coming from the pipeline,
/// then accumulate the values in the valueList and set the variable during
/// EndProcessing().
/// If name is not a formal parameter, then set
/// the variable each time ProcessRecord is called.
/// </summary>
///
protected override void ProcessRecord()
{
if (_nameIsFormalParameter && _valueIsFormalParameter)
{
return;
}
if (_nameIsFormalParameter && !_valueIsFormalParameter)
{
if (Value != AutomationNull.Value)
{
if (_valueList == null)
{
_valueList = new ArrayList();
}
_valueList.Add(Value);
}
}
else
{
SetVariable(Name, Value);
}
}
private ArrayList _valueList;
/// <summary>
/// Sets the variable if the name was specified as a formal parameter
/// but the value came from the pipeline.
/// </summary>
protected override void EndProcessing()
{
if (_nameIsFormalParameter)
{
if (_valueIsFormalParameter)
{
SetVariable(Name, Value);
}
else
{
if (_valueList != null)
{
if (_valueList.Count == 1)
{
SetVariable(Name, _valueList[0]);
}
else if (_valueList.Count == 0)
{
SetVariable(Name, AutomationNull.Value);
}
else
{
SetVariable(Name, _valueList.ToArray());
}
}
else
{
SetVariable(Name, AutomationNull.Value);
}
}
}
}
/// <summary>
/// Sets the variables of the given names to the specified value.
/// </summary>
///
/// <param name="varNames">
/// The name(s) of the variables to set.
/// </param>
///
/// <param name="varValue">
/// The value to set the variable to.
/// </param>
///
private void SetVariable(string[] varNames, object varValue)
{
CommandOrigin origin = MyInvocation.CommandOrigin;
foreach (string varName in varNames)
{
// First look for existing variables to set.
List<PSVariable> matchingVariables = new List<PSVariable>();
bool wasFiltered = false;
if (!String.IsNullOrEmpty(Scope))
{
// We really only need to find matches if the scope was specified.
// If the scope wasn't specified then we need to create the
// variable in the local scope.
matchingVariables =
GetMatchingVariables(varName, Scope, out wasFiltered, /* quiet */ false);
}
else
{
// Since the scope wasn't specified, it doesn't matter if there
// is a variable in another scope, it only matters if there is a
// variable in the local scope.
matchingVariables =
GetMatchingVariables(
varName,
System.Management.Automation.StringLiterals.Local,
out wasFiltered,
false);
}
// We only want to create the variable if we are not filtering
// the name.
if (matchingVariables.Count == 0 &&
!wasFiltered)
{
try
{
ScopedItemOptions newOptions = ScopedItemOptions.None;
if (!String.IsNullOrEmpty(Scope) &&
String.Equals("private", Scope, StringComparison.OrdinalIgnoreCase))
{
newOptions = ScopedItemOptions.Private;
}
if (_options != null)
{
newOptions |= (ScopedItemOptions)_options;
}
object newVarValue = varValue;
if (newVarValue == AutomationNull.Value)
{
newVarValue = null;
}
PSVariable varToSet =
new PSVariable(
varName,
newVarValue,
newOptions);
if (Description == null)
{
Description = String.Empty;
}
varToSet.Description = Description;
// If visibility was specified, set it on the variable
if (_visibility != null)
{
varToSet.Visibility = Visibility;
}
string action = VariableCommandStrings.SetVariableAction;
string target = StringUtil.Format(VariableCommandStrings.SetVariableTarget, varName, newVarValue);
if (ShouldProcess(target, action))
{
object result = null;
if (String.IsNullOrEmpty(Scope))
{
result =
SessionState.Internal.SetVariable(varToSet, Force, origin);
}
else
{
result =
SessionState.Internal.SetVariableAtScope(varToSet, Scope, Force, origin);
}
if (_passThru && result != null)
{
WriteObject(result);
}
}
}
catch (SessionStateException sessionStateException)
{
WriteError(
new ErrorRecord(
sessionStateException.ErrorRecord,
sessionStateException));
continue;
}
catch (PSArgumentException argException)
{
WriteError(
new ErrorRecord(
argException.ErrorRecord,
argException));
continue;
}
}
else
{
foreach (PSVariable matchingVariable in matchingVariables)
{
string action = VariableCommandStrings.SetVariableAction;
string target = StringUtil.Format(VariableCommandStrings.SetVariableTarget, matchingVariable.Name, varValue);
if (ShouldProcess(target, action))
{
object result = null;
try
{
// Since the variable existed in the specified scope, or
// in the local scope if no scope was specified, use
// the reference returned to set the variable properties.
// If we want to force setting over a readonly variable
// we have to temporarily mark the variable writable.
bool wasReadOnly = false;
if (Force &&
(matchingVariable.Options & ScopedItemOptions.ReadOnly) != 0)
{
matchingVariable.SetOptions(matchingVariable.Options & ~ScopedItemOptions.ReadOnly, true);
wasReadOnly = true;
}
// Now change the value, options, or description
// and set the variable
if (varValue != AutomationNull.Value)
{
matchingVariable.Value = varValue;
}
if (Description != null)
{
matchingVariable.Description = Description;
}
if (_options != null)
{
matchingVariable.Options = (ScopedItemOptions)_options;
}
else
{
if (wasReadOnly)
{
matchingVariable.SetOptions(matchingVariable.Options | ScopedItemOptions.ReadOnly, true);
}
}
// If visibility was specified, set it on the variable
if (_visibility != null)
{
matchingVariable.Visibility = Visibility;