forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComputer.cs
More file actions
6950 lines (6225 loc) · 296 KB
/
Copy pathComputer.cs
File metadata and controls
6950 lines (6225 loc) · 296 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
#if !UNIX
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Microsoft.Win32;
using Microsoft.PowerShell.Commands.Internal;
using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Options;
using System.Linq;
using Dbg = System.Management.Automation;
#if CORECLR
using Microsoft.PowerShell.CoreClr.Stubs;
#else
//TODO:CORECLR System.DirectoryServices is not available on CORE CLR
using System.DirectoryServices;
//TODO:CORECLR System.Security.Permission is not available on CORE CLR
using System.Security.Permissions;
using System.Management; // We are not porting the library to CoreCLR
using Microsoft.WSMan.Management;
#endif
// FxCop suppressions for resource strings:
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "ComputerResources.resources", MessageId = "unjoined")]
[module: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", Scope = "resource", Target = "ComputerResources.resources", MessageId = "UpTime")]
namespace Microsoft.PowerShell.Commands
{
#region Test-Connection
/// <summary>
/// This cmdlet is used to test whether a particular host is reachable across an
/// IP network. It works by sending ICMP "echo request" packets to the target
/// host and listening for ICMP "echo response" replies. This cmdlet prints a
/// statistical summary when finished.
/// </summary>
[Cmdlet(VerbsDiagnostic.Test, "Connection", DefaultParameterSetName = RegularParameterSet,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135266", RemotingCapability = RemotingCapability.OwnedByCommand)]
[OutputType(typeof(Boolean))]
[OutputType(@"System.Management.ManagementObject#root\cimv2\Win32_PingStatus")]
public class TestConnectionCommand : PSCmdlet
{
#region "Parameters"
private const string RegularParameterSet = "Default";
private const string QuietParameterSet = "Quiet";
private const string SourceParameterSet = "Source";
/// <summary>
///
/// </summary>
[Parameter(ParameterSetName = SourceParameterSet)]
[Parameter(ParameterSetName = RegularParameterSet)]
public SwitchParameter AsJob { get; set; } = false;
/// <summary>
/// The following is the definition of the input parameter "DcomAuthentication".
/// Specifies the authentication level to be used with WMI connection. Valid
/// values are:
///
/// Unchanged = -1,
/// Default = 0,
/// None = 1,
/// Connect = 2,
/// Call = 3,
/// Packet = 4,
/// PacketIntegrity = 5,
/// PacketPrivacy = 6.
/// </summary>
[Parameter]
[Alias("Authentication")]
public AuthenticationLevel DcomAuthentication { get; set; } = AuthenticationLevel.Packet;
/// <summary>
/// The authentication options for CIM_WSMan connection
/// </summary>
[Parameter]
[ValidateSet(
"Default",
"Basic",
"Negotiate", // can be used with and without credential (without -> PSRP mapped to NegotiateWithImplicitCredential)
"CredSSP",
"Digest",
"Kerberos")] // can be used with and without credential (not sure about implications)
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public string WsmanAuthentication { get; set; } = "Default";
/// <summary>
/// Specify the protocol to use
/// </summary>
[Parameter]
[ValidateSet(ComputerWMIHelper.DcomProtocol, ComputerWMIHelper.WsmanProtocol)]
public string Protocol { get; set; } =
#if CORECLR
//CoreClr does not support DCOM protocol
// This change makes sure that the the command works seamlessly if user did not explicitly entered the protocol
ComputerWMIHelper.WsmanProtocol;
#else
ComputerWMIHelper.DcomProtocol;
#endif
/// <summary>
/// The following is the definition of the input parameter "BufferSize".
/// Buffer size sent with the this command. The default value is 32.
/// </summary>
[Parameter]
[Alias("Size", "Bytes", "BS")]
[ValidateRange((int)0, (int)65500)]
public Int32 BufferSize { get; set; } = 32;
/// <summary>
/// The following is the definition of the input parameter "TimeOut".
/// Time-out value in milliseconds. If a response is not received in this time, no response is assumed. The default is 1000 milliseconds.
/// </summary>
[Parameter]
[ValidateRange((int)1, Int32.MaxValue)]
public Int32 TimeOut { get; set; } = 1000;
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// Value of the address requested. The form of the value can be either the
/// computer name ("wxyz1234"), IPv4 address ("192.168.177.124"), or IPv6
/// address ("2010:836B:4179::836B:4179").
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[Alias("CN", "IPAddress", "__SERVER", "Server", "Destination")]
public String[] ComputerName { get; set; }
/// <summary>
/// The following is the definition of the input parameter "Count".
/// Number of echo requests to send.
/// </summary>
[Parameter]
[ValidateRange(1, UInt32.MaxValue)]
public Int32 Count { get; set; } = 4;
/// <summary>
/// The following is the definition of the input parameter "Credential".
/// Specifies a user account that has permission to perform this action. Type a
/// user-name, such as "User01" or "Domain01\User01", or enter a PSCredential
/// object, such as one from the Get-Credential cmdlet
/// </summary>
[Parameter(ParameterSetName = SourceParameterSet, Mandatory = false)]
[ValidateNotNullOrEmpty]
[Credential]
public PSCredential Credential { get; set; }
/// <summary>
/// The following is the definition of the input parameter "FromComputerName".
/// Specifies the Computer names where the ping request is originated from.
/// </summary>
[Parameter(Position = 1, ParameterSetName = SourceParameterSet, Mandatory = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[Alias("FCN", "SRC")]
public String[] Source { get; set; } = new string[] { "." };
/// <summary>
/// The following is the definition of the input parameter "Impersonation".
/// Specifies the impersonation level to use when calling the WMI method. Valid
/// values are:
///
/// Default = 0,
/// Anonymous = 1,
/// Identify = 2,
/// Impersonate = 3,
/// Delegate = 4.
/// </summary>
[Parameter]
public ImpersonationLevel Impersonation { get; set; } = ImpersonationLevel.Impersonate;
/// <summary>
/// The following is the definition of the input parameter "ThrottleLimit".
/// The number of concurrent computers on which the command will be allowed to
/// execute
/// </summary>
[Parameter(ParameterSetName = SourceParameterSet)]
[Parameter(ParameterSetName = RegularParameterSet)]
[ValidateRange(int.MinValue, (int)1000)]
public Int32 ThrottleLimit
{
get { return throttlelimit; }
set
{
throttlelimit = value;
if (throttlelimit <= 0)
throttlelimit = 32;
}
}
private Int32 throttlelimit = 32;
/// <summary>
/// The following is the definition of the input parameter "TimeToLive".
/// Life span of the packet in seconds. The value is treated as an upper limit.
/// All routers must decrement this value by 1 (one). When this value becomes 0
/// (zero), the packet is dropped by the router. The default value is 80
/// seconds. The hops between routers rarely take this amount of time.
/// </summary>
[Parameter]
[ValidateRange(1, (int)255)]
[Alias("TTL")]
public Int32 TimeToLive { get; set; } = 80;
/// <summary>
/// delay parameter
/// </summary>
[Parameter]
[ValidateRange(1, 60)]
public Int32 Delay { get; set; } = 1;
/// <summary>
/// quiet parameter
/// </summary>
[Parameter(ParameterSetName = QuietParameterSet)]
public SwitchParameter Quiet
{
get { return quiet; }
set { quiet = value; }
}
private bool quiet = false;
#endregion "parameters"
#region "Overrides"
#if !CORECLR
///// <summary>
///// To Store the output for each ping reply
///// </summary>
private ManagementObjectSearcher searcher;
#endif
private TransportProtocol _transportProtocol = TransportProtocol.DCOM;
private readonly CancellationTokenSource cancel = new CancellationTokenSource();
private Dictionary<string, bool> quietResults = new Dictionary<string, bool>();
/// <summary>
/// To begin processing Test-connection
/// </summary>
protected override void BeginProcessing()
{
base.BeginProcessing();
// Verify parameter set
bool haveProtocolParam = this.MyInvocation.BoundParameters.ContainsKey("Protocol");
bool haveWsmanAuthenticationParam = this.MyInvocation.BoundParameters.ContainsKey("WsmanAuthentication");
bool haveDcomAuthenticationParam = this.MyInvocation.BoundParameters.ContainsKey("DcomAuthentication");
bool haveDcomImpersonation = this.MyInvocation.BoundParameters.ContainsKey("Impersonation");
_transportProtocol = (this.Protocol.Equals(ComputerWMIHelper.WsmanProtocol, StringComparison.OrdinalIgnoreCase) || (haveWsmanAuthenticationParam && !haveProtocolParam)) ?
TransportProtocol.WSMan : TransportProtocol.DCOM;
if (haveWsmanAuthenticationParam && (haveDcomAuthenticationParam || haveDcomImpersonation))
{
string errMsg = StringUtil.Format(ComputerResources.StopCommandParamWSManAuthConflict, ComputerResources.StopCommandParamMessage);
ThrowTerminatingError(
new ErrorRecord(
new PSArgumentException(errMsg),
"InvalidParameter",
ErrorCategory.InvalidArgument,
this));
}
if ((_transportProtocol == TransportProtocol.DCOM) && haveWsmanAuthenticationParam)
{
string errMsg = StringUtil.Format(ComputerResources.StopCommandWSManAuthProtocolConflict, ComputerResources.StopCommandParamMessage);
ThrowTerminatingError(
new ErrorRecord(
new PSArgumentException(errMsg),
"InvalidParameter",
ErrorCategory.InvalidArgument,
this));
}
if ((_transportProtocol == TransportProtocol.WSMan) && (haveDcomAuthenticationParam || haveDcomImpersonation))
{
string errMsg = StringUtil.Format(ComputerResources.StopCommandAuthProtocolConflict, ComputerResources.StopCommandParamMessage);
ThrowTerminatingError(
new ErrorRecord(
new PSArgumentException(errMsg),
"InvalidParameter",
ErrorCategory.InvalidArgument,
this));
}
#if CORECLR
if (this.MyInvocation.BoundParameters.ContainsKey("DcomAuthentication"))
{
string errMsg = StringUtil.Format(ComputerResources.InvalidParameterForCoreClr, "DcomAuthentication");
PSArgumentException ex = new PSArgumentException(errMsg, ComputerResources.InvalidParameterForCoreClr);
ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForCoreClr", ErrorCategory.InvalidArgument, null));
}
if (this.MyInvocation.BoundParameters.ContainsKey("Impersonation"))
{
string errMsg = StringUtil.Format(ComputerResources.InvalidParameterForCoreClr, "Impersonation");
PSArgumentException ex = new PSArgumentException(errMsg, ComputerResources.InvalidParameterForCoreClr);
ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForCoreClr", ErrorCategory.InvalidArgument, null));
}
if(this.Protocol.Equals(ComputerWMIHelper.DcomProtocol , StringComparison.OrdinalIgnoreCase))
{
InvalidOperationException ex = new InvalidOperationException(ComputerResources.InvalidParameterDCOMNotSupported);
ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterDCOMNotSupported", ErrorCategory.InvalidOperation, null));
}
#endif
//testing
}
/// <summary>
/// Process Record
/// </summary>
protected override void ProcessRecord()
{
switch (_transportProtocol)
{
#if !CORECLR
case TransportProtocol.DCOM:
processDCOMProtocolForTestConnection();
break;
#endif
case TransportProtocol.WSMan:
ProcessWSManProtocolForTestConnection();
break;
}
}
/// <summary>
/// to implement ^C
/// </summary>
protected override void StopProcessing()
{
#if !CORECLR
ManagementObjectSearcher stopSearcher = searcher;
if (stopSearcher != null)
{
try
{
stopSearcher.Dispose();
}
catch (ObjectDisposedException) { }
}
#endif
try
{
cancel.Cancel();
}
catch (ObjectDisposedException) { }
catch (AggregateException) { }
}
#endregion
#region "Private Methods "
private string QueryString(string[] machinenames, bool escaperequired, bool selectrequired)
{
StringBuilder FilterString = new StringBuilder();
if (selectrequired)
{
FilterString.Append("Select * from ");
FilterString.Append(ComputerWMIHelper.WMI_Class_PingStatus);
FilterString.Append(" where ");
}
FilterString.Append("((");
for (int i = 0; i <= machinenames.Length - 1; i++)
{
FilterString.Append("Address='");
string EscapeComp = machinenames[i].ToString();
if (EscapeComp.Equals(".", StringComparison.CurrentCultureIgnoreCase))
EscapeComp = "localhost";
if (escaperequired)
{
EscapeComp = EscapeComp.Replace("\\", "\\\\'").ToString();
EscapeComp = EscapeComp.Replace("'", "\\'").ToString();
}
FilterString.Append(EscapeComp.ToString());
FilterString.Append("'");
if (i < machinenames.Length - 1)
{
FilterString.Append(" Or ");
}
}
FilterString.Append(")");
FilterString.Append(" And ");
FilterString.Append("TimeToLive=");
FilterString.Append(TimeToLive);
FilterString.Append(" And ");
FilterString.Append("BufferSize=");
FilterString.Append(BufferSize);
FilterString.Append(" And ");
FilterString.Append("TimeOut=");
FilterString.Append(TimeOut);
FilterString.Append(")");
return FilterString.ToString();
}
private void ProcessPingStatus(Object pingStatusObj)
{
Dbg.Diagnostics.Assert(pingStatusObj != null, "Caller should verify that pingStatus != null");
//Dbg.Diagnostics.Assert(pingStatusObj.ClassPath.ClassName.Equals("Win32_PingStatus"), "Caller should verify that pingStatus is a Win32_PingStatus object");
string destinationAddress = null;
UInt32 primaryAddressResolutionStatus;
UInt32 statusCode;
#if !CORECLR
if (_transportProtocol == TransportProtocol.DCOM)
{
ManagementBaseObject pingStatus = (ManagementBaseObject)pingStatusObj;
destinationAddress = (string)LanguagePrimitives.ConvertTo(
pingStatus.GetPropertyValue("Address"),
typeof(string),
CultureInfo.InvariantCulture);
primaryAddressResolutionStatus = (UInt32)LanguagePrimitives.ConvertTo(
pingStatus.GetPropertyValue("PrimaryAddressResolutionStatus"),
typeof(UInt32),
CultureInfo.InvariantCulture);
statusCode = (UInt32)LanguagePrimitives.ConvertTo(
pingStatus.GetPropertyValue("StatusCode"),
typeof(UInt32),
CultureInfo.InvariantCulture);
}
else
{
#endif
CimInstance pingStatus = (CimInstance)pingStatusObj;
destinationAddress = (string)LanguagePrimitives.ConvertTo(
pingStatus.CimInstanceProperties["Address"].Value.ToString(),
typeof(string),
CultureInfo.InvariantCulture);
primaryAddressResolutionStatus = (UInt32)LanguagePrimitives.ConvertTo(
pingStatus.CimInstanceProperties["PrimaryAddressResolutionStatus"].Value,
typeof(UInt32),
CultureInfo.InvariantCulture);
statusCode = (UInt32)LanguagePrimitives.ConvertTo(
pingStatus.CimInstanceProperties["StatusCode"].Value,
typeof(UInt32),
CultureInfo.InvariantCulture);
#if !CORECLR
}
#endif
if (primaryAddressResolutionStatus != 0)
{
if (!quiet)
{
Win32Exception win32Exception = new Win32Exception(unchecked((int)primaryAddressResolutionStatus));
string message = StringUtil.Format(ComputerResources.NoPingResult, destinationAddress, win32Exception.Message);
Exception pingException = new System.Net.NetworkInformation.PingException(message, win32Exception);
ErrorRecord errorRecord = new ErrorRecord(pingException, "TestConnectionException", ErrorCategory.ResourceUnavailable, destinationAddress);
WriteError(errorRecord);
}
}
else
{
if (statusCode != 0)
{
if (!quiet)
{
Win32Exception win32Exception = new Win32Exception(unchecked((int)statusCode));
string message = StringUtil.Format(ComputerResources.NoPingResult, destinationAddress, win32Exception.Message);
Exception pingException = new System.Net.NetworkInformation.PingException(message, win32Exception);
ErrorRecord errorRecord = new ErrorRecord(pingException, "TestConnectionException", ErrorCategory.ResourceUnavailable, destinationAddress);
WriteError(errorRecord);
}
}
else
{
this.quietResults[destinationAddress] = true;
if (!quiet)
{
WriteObject(pingStatusObj);
}
}
}
}
#if !CORECLR
private void processDCOMProtocolForTestConnection()
{
ConnectionOptions options = ComputerWMIHelper.GetConnectionOptions(DcomAuthentication, this.Impersonation, this.Credential);
if (AsJob)
{
string filter = QueryString(ComputerName, true, false);
GetWmiObjectCommand WMICmd = new GetWmiObjectCommand();
WMICmd.Filter = filter.ToString();
WMICmd.Class = ComputerWMIHelper.WMI_Class_PingStatus;
WMICmd.ComputerName = Source;
WMICmd.Authentication = DcomAuthentication;
WMICmd.Impersonation = Impersonation;
WMICmd.ThrottleLimit = throttlelimit;
PSWmiJob wmiJob = new PSWmiJob(WMICmd, Source, throttlelimit, this.MyInvocation.MyCommand.Name, Count);
this.JobRepository.Add(wmiJob);
WriteObject(wmiJob);
}
else
{
int sourceCount = 0;
foreach (string fromcomp in Source)
{
try
{
sourceCount++;
EnumerationOptions enumOptions = new EnumerationOptions();
enumOptions.UseAmendedQualifiers = true;
enumOptions.DirectRead = true;
int destCount = 0;
foreach (var tocomp in ComputerName)
{
destCount++;
string querystring = QueryString(new string[] { tocomp }, true, true);
ObjectQuery query = new ObjectQuery(querystring);
ManagementScope scope = new ManagementScope(ComputerWMIHelper.GetScopeString(fromcomp, ComputerWMIHelper.WMI_Path_CIM), options);
scope.Options.EnablePrivileges = true;
scope.Connect();
using (searcher = new ManagementObjectSearcher(scope, query, enumOptions))
{
for (int j = 0; j <= Count - 1; j++)
{
using (ManagementObjectCollection mobj = searcher.Get())
{
int mobjCount = 0;
foreach (ManagementBaseObject obj in mobj)
{
using (obj)
{
mobjCount++;
ProcessPingStatus(obj);
// to delay the request, if case to avoid the delay for the last pingrequest
if (mobjCount < mobj.Count || j < Count - 1 || sourceCount < Source.Length || destCount < ComputerName.Length)
Thread.Sleep(Delay * 1000);
}
}
}
}
}
}
searcher = null;
}
catch (ManagementException e)
{
ErrorRecord errorRecord = new ErrorRecord(e, "TestConnectionException", ErrorCategory.InvalidOperation, null);
WriteError(errorRecord);
continue;
}
catch (System.Runtime.InteropServices.COMException e)
{
ErrorRecord errorRecord = new ErrorRecord(e, "TestConnectionException", ErrorCategory.InvalidOperation, null);
WriteError(errorRecord);
continue;
}
}
}
if (quiet)
{
foreach (string destinationAddress in this.ComputerName)
{
bool destinationResult = false;
this.quietResults.TryGetValue(destinationAddress, out destinationResult);
WriteObject(destinationResult);
}
}
}
#endif
private void ProcessWSManProtocolForTestConnection()
{
if (AsJob)
{
// TODO: Need job for MI.Net WSMan protocol
// Early return of job object.
throw new PSNotSupportedException();
}
var operationOptions = new CimOperationOptions
{
Timeout = TimeSpan.FromMilliseconds(2000),
CancellationToken = cancel.Token
};
int destCount = 0;
int sourceCount = 0;
foreach (string sourceComp in Source)
{
try
{
sourceCount++;
string sourceMachine;
if ((sourceComp.Equals("localhost", StringComparison.CurrentCultureIgnoreCase)) || (sourceComp.Equals(".", StringComparison.OrdinalIgnoreCase)))
{
sourceMachine = Dns.GetHostName();
}
else
{
sourceMachine = sourceComp;
}
foreach (var tocomp in ComputerName)
{
destCount++;
string querystring = QueryString(new string[] { tocomp }, true, true);
using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(sourceComp, this.Credential, WsmanAuthentication, cancel.Token, this))
{
WriteVerbose(String.Format("WMI query {0} sent to {1}", querystring, sourceComp));
for (int echoRequestCount = 0; echoRequestCount < Count; echoRequestCount++)
{
IEnumerable<CimInstance> mCollection = cimSession.QueryInstances(
ComputerWMIHelper.CimOperatingSystemNamespace,
ComputerWMIHelper.CimQueryDialect,
querystring,
operationOptions);
int total = mCollection.ToList().Count;
int cimInsCount = 1;
foreach (CimInstance obj in mCollection)
{
ProcessPingStatus(obj);
cimInsCount++;
// to delay the request, if case to avoid the delay for the last pingrequest
if (cimInsCount < total || echoRequestCount < Count - 1 || sourceCount < Source.Length || destCount < ComputerName.Length)
Thread.Sleep(Delay * 1000);
}
}
}
}
}
catch (CimException ex)
{
ErrorRecord errorRecord = new ErrorRecord(ex, "TestConnectionException", ErrorCategory.InvalidOperation, null);
WriteError(errorRecord);
continue;
}
catch (System.Runtime.InteropServices.COMException e)
{
ErrorRecord errorRecord = new ErrorRecord(e, "TestConnectionException", ErrorCategory.InvalidOperation, null);
WriteError(errorRecord);
continue;
}
}
if (quiet)
{
foreach (string destinationAddress in this.ComputerName)
{
bool destinationResult = false;
this.quietResults.TryGetValue(destinationAddress, out destinationResult);
WriteObject(destinationResult);
}
}
}
#endregion "Private Methods "
}
#endregion Test-Connection
#if !CORECLR
#region Enable-ComputerRestore
/// <summary>
/// Cmdlet for Enable-ComputerRestore
/// </summary>
[Cmdlet(VerbsLifecycle.Enable, "ComputerRestore", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135209")]
public sealed class EnableComputerRestoreCommand : PSCmdlet, IDisposable
{
#region Parameters
/// <summary>
/// Specifies the Drive on which the system restore will be enabled.
/// The drive string should be of the form "C:\".
/// </summary>
[Parameter(Position = 0, Mandatory = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Drive { get; set; }
#endregion Parameters
private const string ErrorBase = "ComputerResources";
private ManagementClass WMIClass;
#region "IDisposable Members"
/// <summary>
/// Dispose Method
/// </summary>
public void Dispose()
{
this.Dispose(true);
// Use SuppressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose Method.
/// </summary>
/// <param name="disposing"></param>
public void Dispose(bool disposing)
{
if (disposing)
{
if (WMIClass != null)
{
WMIClass.Dispose();
}
}
}
#endregion "IDisposable Members"
#region Overrides
/// <summary>
/// To Enable the Restore Point of the drives
/// </summary>
protected override void BeginProcessing()
{
// system restore APIs are not supported on ARM platform
if (ComputerWMIHelper.SkipSystemRestoreOperationForARMPlatform(this))
{
return;
}
ManagementScope scope = new ManagementScope(ComputerWMIHelper.WMI_Path_Default);
scope.Connect();
WMIClass = new ManagementClass(ComputerWMIHelper.WMI_Class_SystemRestore);
WMIClass.Scope = scope;
int retValue;
//get the system drive
string sysdrive = System.Environment.ExpandEnvironmentVariables("%SystemDrive%");
sysdrive = String.Concat(new string[] { sysdrive, "\\" });
if (ComputerWMIHelper.ContainsSystemDrive(Drive, sysdrive))
{
object[] input = { sysdrive };
try
{
retValue = Convert.ToInt32(WMIClass.InvokeMethod("Enable", input), System.Globalization.CultureInfo.CurrentCulture);
//if success (return value is 0 or if already enabled (error code is 1056 in XP and 0 in vista)
if ((retValue.Equals(0)) || (retValue.Equals(ComputerWMIHelper.ErrorCode_Service)))
{
string driveNew;
foreach (string drive in Drive) //for each input drive
{
if (!ShouldProcess(drive))
{
continue;
}
if (!drive.EndsWith("\\", StringComparison.CurrentCultureIgnoreCase))
{
driveNew = String.Concat(drive, "\\");
}
else
driveNew = drive;
if (!ComputerWMIHelper.IsValidDrive(driveNew))//if not valid drive,throw error
{
Exception Ex = new ArgumentException(StringUtil.Format(ComputerResources.InvalidDrive, drive));
WriteError(new ErrorRecord(Ex, "EnableComputerRestoreInvalidDrive", ErrorCategory.InvalidData, null));
continue;
}
//parameter for Enable method
//if the input drive is not system drive
if (!driveNew.Equals(sysdrive, StringComparison.OrdinalIgnoreCase))
{
object[] inputDrive = { driveNew };
retValue = Convert.ToInt32(WMIClass.InvokeMethod("Enable", inputDrive), System.Globalization.CultureInfo.CurrentCulture);
//if not enabled, retry again
if (retValue.Equals(ComputerWMIHelper.ErrorCode_Interface))
{
retValue = Convert.ToInt32(WMIClass.InvokeMethod("Enable", inputDrive), System.Globalization.CultureInfo.CurrentCulture);
}
}
//if not success and if it is not already enabled (error code is 1056 in XP)
// Error 1717 - The interface is unknown. Even though this comes sometimes . The Drive is getting enabled.
if (!(retValue.Equals(0)) && !(retValue.Equals(ComputerWMIHelper.ErrorCode_Service)) && !(retValue.Equals(ComputerWMIHelper.ErrorCode_Interface)))
{
Exception Ex = new ArgumentException(StringUtil.Format(ComputerResources.NotEnabled, drive));
WriteError(new ErrorRecord(Ex, "EnableComputerRestoreNotEnabled", ErrorCategory.InvalidOperation, null));
continue;
}
}
}
else
{
ArgumentException Ex = new ArgumentException(StringUtil.Format(ComputerResources.NotEnabled, sysdrive));
WriteError(new ErrorRecord(Ex, "EnableComputerRestoreNotEnabled", ErrorCategory.InvalidOperation, null));
}
}
catch (ManagementException e)
{
if ((e.ErrorCode.Equals(ManagementStatus.NotFound)) || (e.ErrorCode.Equals(ManagementStatus.InvalidClass)))
{
ErrorRecord er = new ErrorRecord(new ArgumentException(StringUtil.Format(ComputerResources.NotSupported)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
}
else
{
ErrorRecord errorRecord = new ErrorRecord(e, "GetWMIManagementException", ErrorCategory.InvalidOperation, null);
WriteError(errorRecord);
}
}
catch (COMException e)
{
if (string.IsNullOrEmpty(e.Message))
{
Exception Ex = new ArgumentException(StringUtil.Format(ComputerResources.SystemRestoreServiceDisabled));
WriteError(new ErrorRecord(Ex, "ServiceDisabled", ErrorCategory.InvalidOperation, null));
}
else
{
ErrorRecord errorRecord = new ErrorRecord(e, "COMException", ErrorCategory.InvalidOperation, null);
WriteError(errorRecord);
}
}
}
else
{
ArgumentException Ex = new ArgumentException(StringUtil.Format(ComputerResources.NoSystemDrive));
WriteError(new ErrorRecord(Ex, "EnableComputerNoSystemDrive", ErrorCategory.InvalidArgument, null));
}
}//end of BeginProcessing
/// <summary>
/// to implement ^C
/// </summary>
protected override void StopProcessing()
{
if (WMIClass != null)
{
WMIClass.Dispose();
}
}
#endregion Overrides
}//end of class
#endregion
#region Disable-ComputerRestore
/// <summary>
/// This cmdlet is to Disable Computer Restore points.
/// </summary>
[Cmdlet(VerbsLifecycle.Disable, "ComputerRestore", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135207")]
public sealed class DisableComputerRestoreCommand : PSCmdlet, IDisposable
{
#region Parameters
/// <summary>
/// Specifies the Drive on which the system restore will be enabled.
/// The drive string should be of the form "C:\".
/// </summary>
[Parameter(Position = 0, Mandatory = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Drive { get; set; }
#endregion Parameters
private ManagementClass WMIClass;
private const string ErrorBase = "ComputerResources";
#region "IDisposable Members"
/// <summary>
/// Dispose Method
/// </summary>
public void Dispose()
{
this.Dispose(true);
// Use SuppressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose Method.
/// </summary>
/// <param name="disposing"></param>
public void Dispose(bool disposing)
{
if (disposing)
{
if (WMIClass != null)
{
WMIClass.Dispose();
}
}
}
#endregion "IDisposable Members"
#region Overrides
/// <summary>
/// To Disable the Restore Point of the drives
/// </summary>
protected override void BeginProcessing()
{
// system restore APIs are not supported on ARM platform
if (ComputerWMIHelper.SkipSystemRestoreOperationForARMPlatform(this))
{
return;
}
ManagementScope scope = new ManagementScope(ComputerWMIHelper.WMI_Path_Default);
scope.Connect();
WMIClass = new ManagementClass(ComputerWMIHelper.WMI_Class_SystemRestore);
WMIClass.Scope = scope;
string driveNew;
foreach (string drive in Drive)
{
if (!ShouldProcess(drive))
{
continue;
}
if (!drive.EndsWith("\\", StringComparison.CurrentCultureIgnoreCase))
{
driveNew = String.Concat(drive, "\\");
}
else
driveNew = drive;
if (!ComputerWMIHelper.IsValidDrive(driveNew))
{
ErrorRecord er = new ErrorRecord(new ArgumentException(StringUtil.Format(ComputerResources.NotValidDrive, drive)), null, ErrorCategory.InvalidData, null);
WriteError(er);
continue;
}
else
{
try
{
object[] input = { driveNew };
int retValue = Convert.ToInt32(WMIClass.InvokeMethod("Disable", input), System.Globalization.CultureInfo.CurrentCulture);
// Error 1717 - The interface is unknown. Even though this comes sometimes . The Drive is getting disabled.
if (!(retValue.Equals(0)) && !(retValue.Equals(ComputerWMIHelper.ErrorCode_Interface)))
{
ErrorRecord er = new ErrorRecord(new ArgumentException(StringUtil.Format(ComputerResources.NotDisabled, drive)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
continue;
}
}
catch (ManagementException e)
{
if ((e.ErrorCode.Equals(ManagementStatus.NotFound)) || (e.ErrorCode.Equals(ManagementStatus.InvalidClass)))
{
ErrorRecord er = new ErrorRecord(new ArgumentException(StringUtil.Format(ComputerResources.NotSupported)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
}
else
{
ErrorRecord errorRecord = new ErrorRecord(e, "GetWMIManagementException", ErrorCategory.InvalidOperation, null);
WriteError(errorRecord);
}
}
catch (COMException e)
{
if (string.IsNullOrEmpty(e.Message))
{
Exception Ex = new ArgumentException(StringUtil.Format(ComputerResources.SystemRestoreServiceDisabled));
WriteError(new ErrorRecord(Ex, "ServiceDisabled", ErrorCategory.InvalidOperation, null));
}
else
{
ErrorRecord errorRecord = new ErrorRecord(e, "COMException", ErrorCategory.InvalidOperation, null);
WriteError(errorRecord);
}
}
}
}
}
/// <summary>
/// to implement ^C
/// </summary>
protected override void StopProcessing()
{
if (WMIClass != null)
{
WMIClass.Dispose();