forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPSRemotingCmdlet.cs
More file actions
4544 lines (3929 loc) · 182 KB
/
Copy pathPSRemotingCmdlet.cs
File metadata and controls
4544 lines (3929 loc) · 182 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.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Remoting;
using System.Management.Automation.Remoting.Client;
using System.Management.Automation.Runspaces;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This class defines most of the common functionality used
/// across remoting cmdlets.
///
/// It contains tons of utility functions which are used all
/// across the remoting cmdlets.
/// </summary>
public abstract class PSRemotingCmdlet : PSCmdlet
{
#region Overrides
/// <summary>
/// Verifies if remoting cmdlets can be used.
/// </summary>
protected override void BeginProcessing()
{
if (!SkipWinRMCheck)
{
RemotingCommandUtil.CheckRemotingCmdletPrerequisites();
}
}
#endregion Overrides
#region Utility functions
/// <summary>
/// Handle the object obtained from an ObjectStream's reader
/// based on its type.
/// </summary>
internal void WriteStreamObject(Action<Cmdlet> action)
{
action(this);
}
/// <summary>
/// Resolve all the machine names provided. Basically, if a machine
/// name is '.' assume localhost.
/// </summary>
/// <param name="computerNames">Array of computer names to resolve.</param>
/// <param name="resolvedComputerNames">Resolved array of machine names.</param>
protected void ResolveComputerNames(string[] computerNames, out string[] resolvedComputerNames)
{
if (computerNames == null)
{
resolvedComputerNames = new string[1];
resolvedComputerNames[0] = ResolveComputerName(".");
}
else if (computerNames.Length == 0)
{
resolvedComputerNames = Array.Empty<string>();
}
else
{
resolvedComputerNames = new string[computerNames.Length];
for (int i = 0; i < resolvedComputerNames.Length; i++)
{
resolvedComputerNames[i] = ResolveComputerName(computerNames[i]);
}
}
}
/// <summary>
/// Resolves a computer name. If its null or empty
/// its assumed to be localhost.
/// </summary>
/// <param name="computerName">Computer name to resolve.</param>
/// <returns>Resolved computer name.</returns>
protected string ResolveComputerName(string computerName)
{
Diagnostics.Assert(computerName != null, "Null ComputerName");
if (string.Equals(computerName, ".", StringComparison.OrdinalIgnoreCase))
{
// tracer.WriteEvent(ref PSEventDescriptors.PS_EVENT_HOSTNAMERESOLVE);
// tracer.Dispose();
// tracer.OperationalChannel.WriteVerbose(PSEventId.HostNameResolve, PSOpcode.Method, PSTask.CreateRunspace);
return s_LOCALHOST;
}
else
{
return computerName;
}
}
/// <summary>
/// Load the resource corresponding to the specified errorId and
/// return the message as a string.
/// </summary>
/// <param name="resourceString">resource String which holds the message
/// </param>
/// <returns>Error message loaded from appropriate resource cache.</returns>
internal string GetMessage(string resourceString)
{
string message = GetMessage(resourceString, null);
return message;
}
/// <summary>
/// </summary>
/// <param name="resourceString"></param>
/// <param name="args"></param>
/// <returns></returns>
internal string GetMessage(string resourceString, params object[] args)
{
string message;
if (args != null)
{
message = StringUtil.Format(resourceString, args);
}
else
{
message = resourceString;
}
return message;
}
#endregion Utility functions
#region Private Members
private static readonly string s_LOCALHOST = "localhost";
// private PSETWTracer tracer = PSETWTracer.GetETWTracer(PSKeyword.Cmdlets);
#endregion Private Members
#region Protected Members
/// <summary>
/// Computername parameter set.
/// </summary>
protected const string ComputerNameParameterSet = "ComputerName";
/// <summary>
/// Computername with session instance ID parameter set.
/// </summary>
protected const string ComputerInstanceIdParameterSet = "ComputerInstanceId";
/// <summary>
/// Container ID parameter set.
/// </summary>
protected const string ContainerIdParameterSet = "ContainerId";
/// <summary>
/// VM guid parameter set.
/// </summary>
protected const string VMIdParameterSet = "VMId";
/// <summary>
/// VM name parameter set.
/// </summary>
protected const string VMNameParameterSet = "VMName";
/// <summary>
/// SSH host parameter set.
/// </summary>
protected const string SSHHostParameterSet = "SSHHost";
/// <summary>
/// SSH host parmeter set supporting hash connection parameters.
/// </summary>
protected const string SSHHostHashParameterSet = "SSHHostHashParam";
/// <summary>
/// Runspace parameter set.
/// </summary>
protected const string SessionParameterSet = "Session";
/// <summary>
/// Parameter set to use Windows PowerShell.
/// </summary>
protected const string UseWindowsPowerShellParameterSet = "UseWindowsPowerShellParameterSet";
/// <summary>
/// Default shellname.
/// </summary>
protected const string DefaultPowerShellRemoteShellName = WSManNativeApi.ResourceURIPrefix + "Microsoft.PowerShell";
/// <summary>
/// Default application name for the connection uri.
/// </summary>
protected const string DefaultPowerShellRemoteShellAppName = "WSMan";
#endregion Protected Members
#region Internal Members
/// <summary>
/// Skip checking for WinRM.
/// </summary>
internal bool SkipWinRMCheck { get; set; } = false;
#endregion Internal Members
#region Protected Methods
/// <summary>
/// Determines the shellname to use based on the following order:
/// 1. ShellName parameter specified
/// 2. DEFAULTREMOTESHELLNAME variable set
/// 3. PowerShell.
/// </summary>
/// <returns>The shell to launch in the remote machine.</returns>
protected string ResolveShell(string shell)
{
string resolvedShell;
if (!string.IsNullOrEmpty(shell))
{
resolvedShell = shell;
}
else
{
resolvedShell = (string)SessionState.Internal.ExecutionContext.GetVariableValue(
SpecialVariables.PSSessionConfigurationNameVarPath, DefaultPowerShellRemoteShellName);
}
return resolvedShell;
}
/// <summary>
/// Determines the appname to be used based on the following order:
/// 1. AppName parameter specified
/// 2. DEFAULTREMOTEAPPNAME variable set
/// 3. WSMan.
/// </summary>
/// <param name="appName">Application name to resolve.</param>
/// <returns>Resolved appname.</returns>
protected string ResolveAppName(string appName)
{
string resolvedAppName;
if (!string.IsNullOrEmpty(appName))
{
resolvedAppName = appName;
}
else
{
resolvedAppName = (string)SessionState.Internal.ExecutionContext.GetVariableValue(
SpecialVariables.PSSessionApplicationNameVarPath,
DefaultPowerShellRemoteShellAppName);
}
return resolvedAppName;
}
#endregion
}
/// <summary>
/// Contains SSH connection information.
/// </summary>
internal struct SSHConnection
{
public string ComputerName;
public string UserName;
public string KeyFilePath;
public int Port;
public string Subsystem;
public int ConnectingTimeout;
public Hashtable Options;
}
/// <summary>
/// Base class for any cmdlet which takes a -Session parameter
/// or a -ComputerName parameter (along with its other associated
/// parameters). The following cmdlets currently fall under this
/// category:
/// 1. New-PSSession
/// 2. Invoke-Expression
/// 3. Start-PSJob.
/// </summary>
public abstract class PSRemotingBaseCmdlet : PSRemotingCmdlet
{
#region Enums
/// <summary>
/// State of virtual machine. This is the same as VMState in
/// \vm\ux\powershell\objects\common\Types.cs.
/// </summary>
internal enum VMState
{
/// <summary>
/// Other. Corresponds to CIM_EnabledLogicalElement.EnabledState = Other.
/// </summary>
Other = 1,
/// <summary>
/// Running. Corresponds to CIM_EnabledLogicalElement.EnabledState = Enabled.
/// </summary>
Running = 2,
/// <summary>
/// Off. Corresponds to CIM_EnabledLogicalElement.EnabledState = Disabled.
/// </summary>
Off = 3,
/// <summary>
/// Stopping. Corresponds to CIM_EnabledLogicalElement.EnabledState = ShuttingDown.
/// </summary>
Stopping = 4,
/// <summary>
/// Saved. Corresponds to CIM_EnabledLogicalElement.EnabledState = Enabled but offline.
/// </summary>
Saved = 6,
/// <summary>
/// Paused. Corresponds to CIM_EnabledLogicalElement.EnabledState = Quiesce.
/// </summary>
Paused = 9,
/// <summary>
/// Starting. EnabledStateStarting. State transition from PowerOff or Saved to Running.
/// </summary>
Starting = 10,
/// <summary>
/// Reset. Corresponds to CIM_EnabledLogicalElement.EnabledState = Reset.
/// </summary>
Reset = 11,
/// <summary>
/// Saving. Corresponds to EnabledStateSaving.
/// </summary>
Saving = 32773,
/// <summary>
/// Pausing. Corresponds to EnabledStatePausing.
/// </summary>
Pausing = 32776,
/// <summary>
/// Resuming. Corresponds to EnabledStateResuming.
/// </summary>
Resuming = 32777,
/// <summary>
/// FastSaved. EnabledStateFastSuspend.
/// </summary>
FastSaved = 32779,
/// <summary>
/// FastSaving. EnabledStateFastSuspending.
/// </summary>
FastSaving = 32780,
/// <summary>
/// ForceShutdown. Used to force a graceful shutdown of the virtual machine.
/// </summary>
ForceShutdown = 32781,
/// <summary>
/// ForceReboot. Used to force a graceful reboot of the virtual machine.
/// </summary>
ForceReboot = 32782,
/// <summary>
/// RunningCritical. Critical states.
/// </summary>
RunningCritical,
/// <summary>
/// OffCritical. Critical states.
/// </summary>
OffCritical,
/// <summary>
/// StoppingCritical. Critical states.
/// </summary>
StoppingCritical,
/// <summary>
/// SavedCritical. Critical states.
/// </summary>
SavedCritical,
/// <summary>
/// PausedCritical. Critical states.
/// </summary>
PausedCritical,
/// <summary>
/// StartingCritical. Critical states.
/// </summary>
StartingCritical,
/// <summary>
/// ResetCritical. Critical states.
/// </summary>
ResetCritical,
/// <summary>
/// SavingCritical. Critical states.
/// </summary>
SavingCritical,
/// <summary>
/// PausingCritical. Critical states.
/// </summary>
PausingCritical,
/// <summary>
/// ResumingCritical. Critical states.
/// </summary>
ResumingCritical,
/// <summary>
/// FastSavedCritical. Critical states.
/// </summary>
FastSavedCritical,
/// <summary>
/// FastSavingCritical. Critical states.
/// </summary>
FastSavingCritical,
}
#nullable enable
/// <summary>
/// Get the State property from Get-VM result.
/// </summary>
/// <param name="value">The raw PSObject as returned by Get-VM.</param>
/// <returns>The VMState value of the State property if present and parsable, otherwise null.</returns>
internal VMState? GetVMStateProperty(PSObject value)
{
object? rawState = value.Properties["State"].Value;
if (rawState is Enum enumState)
{
// If the Hyper-V module was directly importable we have the VMState enum
// value which we can just cast to our VMState type.
return (VMState)enumState;
}
else if (rawState is string stringState && Enum.TryParse(stringState, true, out VMState result))
{
// If the Hyper-V module was imported through implicit remoting on old
// Windows versions we get a string back which we will try and parse
// as the enum label.
return result;
}
// Unknown scenario, this should not happen.
string message = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.HyperVFailedToGetStateUnknownType,
rawState?.GetType()?.FullName ?? "null");
throw new InvalidOperationException(message);
}
#nullable disable
#endregion
#region Tracer
// PSETWTracer tracer = PSETWTracer.GetETWTracer(PSKeyword.Runspace);
#endregion Tracer
#region Properties
/// <summary>
/// The PSSession object describing the remote runspace
/// using which the specified cmdlet operation will be performed.
/// </summary>
[Parameter(Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.SessionParameterSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public virtual PSSession[] Session { get; set; }
/// <summary>
/// This parameter represents the address(es) of the remote
/// computer(s). The following formats are supported:
/// (a) Computer name
/// (b) IPv4 address : 132.3.4.5
/// (c) IPv6 address: 3ffe:8311:ffff:f70f:0:5efe:172.30.162.18.
/// </summary>
[Parameter(Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Alias("Cn")]
public virtual string[] ComputerName { get; set; }
/// <summary>
/// Computer names after they have been resolved
/// (null, empty string, "." resolves to localhost)
/// </summary>
/// <remarks>If Null or empty string is specified, then localhost is assumed.
/// The ResolveComputerNames will include this.
/// </remarks>
protected string[] ResolvedComputerNames { get; set; }
/// <summary>
/// Guid of target virtual machine.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Position = 0,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMIdParameterSet)]
[ValidateNotNullOrEmpty]
[Alias("VMGuid")]
public virtual Guid[] VMId { get; set; }
/// <summary>
/// Name of target virtual machine.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)]
[ValidateNotNullOrEmpty]
public virtual string[] VMName { get; set; }
/// <summary>
/// Specifies the credentials of the user to impersonate in the
/// remote machine. If this parameter is not specified then the
/// credentials of the current user process will be assumed.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)]
[Credential()]
public virtual PSCredential Credential
{
get
{
return _pscredential;
}
set
{
_pscredential = value;
ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication);
}
}
private PSCredential _pscredential;
/// <summary>
/// ID of target container.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "This is by spec.")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.ContainerIdParameterSet)]
[ValidateNotNullOrEmpty]
public virtual string[] ContainerId { get; set; }
/// <summary>
/// When set, PowerShell process inside container will be launched with
/// high privileged account.
/// Otherwise (default case), PowerShell process inside container will be launched
/// with low privileged account.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ContainerIdParameterSet)]
public virtual SwitchParameter RunAsAdministrator { get; set; }
/// <summary>
/// Port specifies the alternate port to be used in case the
/// default ports are not used for the transport mechanism
/// (port 80 for http and port 443 for useSSL)
/// </summary>
/// <remarks>
/// Currently this is being accepted as a parameter. But in future
/// support will be added to make this a part of a policy setting.
/// When a policy setting is in place this parameter can be used
/// to override the policy setting
/// </remarks>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
[ValidateRange((int)1, (int)UInt16.MaxValue)]
public virtual int Port { get; set; }
/// <summary>
/// This parameter suggests that the transport scheme to be used for
/// remote connections is useSSL instead of the default http.Since
/// there are only two possible transport schemes that are possible
/// at this point, a SwitchParameter is being used to switch between
/// the two.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")]
public virtual SwitchParameter UseSSL { get; set; }
/// <summary>
/// This parameters specifies the appname which identifies the connection
/// end point on the remote machine. If this parameter is not specified
/// then the value specified in DEFAULTREMOTEAPPNAME will be used. If that's
/// not specified as well, then "WSMAN" will be used.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
public virtual string ApplicationName
{
get
{
return _appName;
}
set
{
_appName = ResolveAppName(value);
}
}
private string _appName;
/// <summary>
/// Allows the user of the cmdlet to specify a throttling value
/// for throttling the number of remote operations that can
/// be executed simultaneously.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SessionParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ContainerIdParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.VMIdParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)]
public virtual int ThrottleLimit { get; set; } = 0;
/// <summary>
/// A complete URI(s) specified for the remote computer and shell to
/// connect to and create runspace for.
/// </summary>
[Parameter(Position = 0, Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
[ValidateNotNullOrEmpty]
[Alias("URI", "CU")]
public virtual Uri[] ConnectionUri { get; set; }
/// <summary>
/// The AllowRedirection parameter enables the implicit redirection functionality.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
public virtual SwitchParameter AllowRedirection
{
get { return _allowRedirection; }
set { _allowRedirection = value; }
}
private bool _allowRedirection = false;
/// <summary>
/// Extended Session Options for controlling the session creation. Use
/// "New-WSManSessionOption" cmdlet to supply value for this parameter.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
[ValidateNotNull]
public virtual PSSessionOption SessionOption
{
get
{
if (_sessionOption == null)
{
object tmp = this.SessionState.PSVariable.GetValue(DEFAULT_SESSION_OPTION);
if (tmp == null || !LanguagePrimitives.TryConvertTo<PSSessionOption>(tmp, out _sessionOption))
{
_sessionOption = new PSSessionOption();
}
}
return _sessionOption;
}
set
{
_sessionOption = value;
}
}
private PSSessionOption _sessionOption;
internal const string DEFAULT_SESSION_OPTION = "PSSessionOption";
// Quota related variables.
/// <summary>
/// Use basic authentication to authenticate the user.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
public virtual AuthenticationMechanism Authentication
{
get
{
return _authMechanism;
}
set
{
_authMechanism = value;
// Validate if a user can specify this authentication.
ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication);
}
}
private AuthenticationMechanism _authMechanism = AuthenticationMechanism.Default;
/// <summary>
/// Specifies the certificate thumbprint to be used to impersonate the user on the
/// remote machine.
/// </summary>
[Parameter(ParameterSetName = NewPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = NewPSSessionCommand.UriParameterSet)]
public virtual string CertificateThumbprint
{
get
{
return _thumbPrint;
}
set
{
_thumbPrint = value;
ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication);
}
}
private string _thumbPrint = null;
#region SSHHostParameters
/// <summary>
/// Host name for an SSH remote connection.
/// </summary>
[Parameter(Position = 0, Mandatory = true,
ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
[ValidateNotNullOrEmpty()]
public virtual string[] HostName
{
get;
set;
}
/// <summary>
/// SSH User Name.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
[ValidateNotNullOrEmpty()]
public virtual string UserName
{
get;
set;
}
/// <summary>
/// SSH Key File Path.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
[ValidateNotNullOrEmpty()]
[Alias("IdentityFilePath")]
public virtual string KeyFilePath
{
get;
set;
}
/// <summary>
/// Gets or sets a value for the SSH subsystem to use for the remote connection.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
public virtual string Subsystem { get; set; }
/// <summary>
/// Gets or sets a value in milliseconds that limits the time allowed for an SSH connection to be established.
/// Default timeout value is infinite.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
public virtual int ConnectingTimeout { get; set; } = Timeout.Infinite;
/// <summary>
/// This parameter specifies that SSH is used to establish the remote
/// connection and act as the remoting transport. By default WinRM is used
/// as the remoting transport. Using the SSH transport requires that SSH is
/// installed and PowerShell remoting is enabled on both client and remote machines.
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)]
[ValidateSet("true")]
public virtual SwitchParameter SSHTransport
{
get;
set;
}
/// <summary>
/// Hashtable array containing SSH connection parameters for each remote target
/// ComputerName (Alias: HostName) (required)
/// UserName (optional)
/// KeyFilePath (Alias: IdentityFilePath) (optional)
/// </summary>
[Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostHashParameterSet, Mandatory = true)]
[ValidateNotNullOrEmpty()]
public virtual Hashtable[] SSHConnection
{
get;
set;
}
/// <summary>
/// Gets or sets the Hashtable containing options to be passed to OpenSSH.
/// </summary>
[Parameter(ParameterSetName = InvokeCommandCommand.SSHHostParameterSet)]
[ValidateNotNullOrEmpty]
public virtual Hashtable Options { get; set; }
#endregion
#endregion Properties
#region Internal Static Methods
/// <summary>
/// Used to resolve authentication from the parameters chosen by the user.
/// User has the following options:
/// 1. AuthMechanism + Credential
/// 2. CertificateThumbPrint
///
/// All the above are mutually exclusive.
/// </summary>
/// <exception cref="InvalidOperationException">
/// If there is ambiguity as specified above.
/// </exception>
internal static void ValidateSpecifiedAuthentication(PSCredential credential, string thumbprint, AuthenticationMechanism authentication)
{
if ((credential != null) && (thumbprint != null))
{
string message = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication,
"CertificateThumbPrint", "Credential");
throw new InvalidOperationException(message);
}
if ((authentication != AuthenticationMechanism.Default) && (thumbprint != null))
{
string message = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication,
"CertificateThumbPrint", authentication.ToString());
throw new InvalidOperationException(message);
}
if ((authentication == AuthenticationMechanism.NegotiateWithImplicitCredential) &&
(credential != null))
{
string message = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication,
"Credential", authentication.ToString());
throw new InvalidOperationException(message);
}
}
#endregion
#region Internal Methods
#region SSH Connection Strings
private const string ComputerNameParameter = "ComputerName";
private const string HostNameAlias = "HostName";
private const string UserNameParameter = "UserName";
private const string KeyFilePathParameter = "KeyFilePath";
private const string IdentityFilePathAlias = "IdentityFilePath";
private const string PortParameter = "Port";
private const string SubsystemParameter = "Subsystem";
private const string ConnectingTimeoutParameter = "ConnectingTimeout";
private const string OptionsParameter = "Options";
#endregion
/// <summary>
/// Parse a hostname used with SSH Transport to get embedded
/// username and/or port.
/// </summary>
/// <param name="hostname">Host name to parse.</param>
/// <param name="host">Resolved target host.</param>
/// <param name="userName">Resolved target user name.</param>
/// <param name="port">Resolved target port.</param>
protected void ParseSshHostName(string hostname, out string host, out string userName, out int port)
{
host = hostname;
userName = this.UserName;
port = this.Port;
try
{
Uri uri = new System.Uri("ssh://" + hostname);
host = ResolveComputerName(uri.Host);
ValidateComputerName(new string[] { host });
if (uri.UserInfo != string.Empty)
{
userName = uri.UserInfo;
}
if (uri.Port != -1)
{
port = uri.Port;
}
}
catch (UriFormatException)
{
ThrowTerminatingError(new ErrorRecord(
new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.InvalidComputerName)), "PSSessionInvalidComputerName",
ErrorCategory.InvalidArgument, hostname));
}
}
/// <summary>
/// Parse the Connection parameter HashTable array.
/// </summary>
/// <returns>Array of SSHConnection objects.</returns>
internal SSHConnection[] ParseSSHConnectionHashTable()
{
List<SSHConnection> connections = new();
foreach (var item in this.SSHConnection)
{
if (item.ContainsKey(ComputerNameParameter) && item.ContainsKey(HostNameAlias))
{
throw new PSArgumentException(RemotingErrorIdStrings.SSHConnectionDuplicateHostName);
}
if (item.ContainsKey(KeyFilePathParameter) && item.ContainsKey(IdentityFilePathAlias))
{
throw new PSArgumentException(RemotingErrorIdStrings.SSHConnectionDuplicateKeyPath);
}
SSHConnection connectionInfo = new();
foreach (var key in item.Keys)
{
string paramName = key as string;
if (string.IsNullOrEmpty(paramName))
{
throw new PSArgumentException(RemotingErrorIdStrings.InvalidSSHConnectionParameter);
}
if (paramName.Equals(ComputerNameParameter, StringComparison.OrdinalIgnoreCase) || paramName.Equals(HostNameAlias, StringComparison.OrdinalIgnoreCase))
{
var resolvedComputerName = ResolveComputerName(GetSSHConnectionStringParameter(item[paramName]));
ParseSshHostName(resolvedComputerName, out string host, out string userName, out int port);
connectionInfo.ComputerName = host;
if (userName != string.Empty)
{
connectionInfo.UserName = userName;
}
if (port != -1)
{
connectionInfo.Port = port;
}
}
else if (paramName.Equals(UserNameParameter, StringComparison.OrdinalIgnoreCase))
{
connectionInfo.UserName = GetSSHConnectionStringParameter(item[paramName]);
}
else if (paramName.Equals(KeyFilePathParameter, StringComparison.OrdinalIgnoreCase) || paramName.Equals(IdentityFilePathAlias, StringComparison.OrdinalIgnoreCase))
{
connectionInfo.KeyFilePath = GetSSHConnectionStringParameter(item[paramName]);
}
else if (paramName.Equals(PortParameter, StringComparison.OrdinalIgnoreCase))