forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigProvider.cs
More file actions
6388 lines (5869 loc) · 290 KB
/
Copy pathConfigProvider.cs
File metadata and controls
6388 lines (5869 loc) · 290 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.Generic;
using System.Collections;
using System.Text;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Collections.ObjectModel;
using System.Xml;
using System.Xml.XPath;
using System.Text.RegularExpressions;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Security;
#if !CORECLR
using System.ServiceProcess;
#endif
namespace Microsoft.WSMan.Management
{
/// <summary>
/// WsMan Provider.
/// </summary>
[CmdletProvider(WSManStringLiterals.ProviderName, ProviderCapabilities.Credentials)]
public sealed partial class WSManConfigProvider : NavigationCmdletProvider, ICmdletProviderSupportsHelp
{
//Plugin Name Storage
private PSObject objPluginNames = null;
/// <summary>
/// Determines if Set-Item user input type validation is required or not.
/// It is True by default, Clear-Item will set it to false so that it can
/// pass Empty String as value for Set-Item.
/// </summary>
private bool clearItemIsCalled = false;
WSManHelper helper = new WSManHelper();
/// <summary>
/// Object contains the cache of the enumerate results for the cmdlet to execute.
/// </summary>
Dictionary<string, XmlDocument> enumerateMapping = new Dictionary<string, XmlDocument>();
/// <summary>
/// Mapping of ResourceURI with the XML returned by the Get call.
/// </summary>
Dictionary<string, string> getMapping = new Dictionary<string, string>();
#region ICmdletProviderSupportsHelp Members
/// <summary>
/// This implements Get-Help for config provider custom path.
/// When user calls "Get-Help new-item" in our config provider path, this function will get called.
/// </summary>
/// <param name="helpItemName"></param>
/// <param name="path"></param>
/// <returns></returns>
string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path)
{
//Get the leaf node from the path for which help is requested.
int ChildIndex = path.LastIndexOf("\\", StringComparison.OrdinalIgnoreCase);
if (ChildIndex == -1)
{
//Means we are at host level, where no new-item is supported. Return empty string.
return String.Empty;
}
String child = path.Substring(ChildIndex + 1);
//We only return help for the below set of 5 commands, not for any other case.
switch (helpItemName)
{
case "New-Item":
case "Get-Item":
case "Set-Item":
case "Clear-Item":
case "Remove-Item":
break;
default:
return String.Empty;
}
// Load the help file from the current UI culture subfolder of the module's root folder
XmlDocument document = new XmlDocument();
CultureInfo culture = Host.CurrentUICulture;
String providerBase = this.ProviderInfo.PSSnapIn != null ? this.ProviderInfo.PSSnapIn.ApplicationBase : this.ProviderInfo.Module.ModuleBase; // "\windows\system32\WindowsPowerShell\v1.0"
String helpFile = null;
do
{
string muiDirectory = Path.Combine(providerBase, culture.Name);
if (Directory.Exists(muiDirectory))
{
string supposedHelpFile = Path.Combine(muiDirectory, this.ProviderInfo.HelpFile);
if (File.Exists(supposedHelpFile))
{
helpFile = supposedHelpFile;
break;
}
}
culture = culture.Parent;
} while (culture != culture.Parent);
if (helpFile == null)
{
//Can't find help file. Return empty string
return String.Empty;
}
try
{
//XmlDocument in CoreCLR does not have file path parameter, use XmlReader
XmlReaderSettings readerSettings = new XmlReaderSettings();
#if !CORECLR
readerSettings.XmlResolver = null;
#endif
using (XmlReader reader = XmlReader.Create(helpFile, readerSettings))
{
document.Load(reader);
}
}
catch(XmlException)
{
return String.Empty;
}
catch(PathTooLongException)
{
return String.Empty;
}
catch(IOException)
{
return String.Empty;
}
catch(UnauthorizedAccessException)
{
return String.Empty;
}
catch(NotSupportedException)
{
return String.Empty;
}
catch(SecurityException)
{
return String.Empty;
}
// Add the "msh" and "command" namespaces from the MAML schema
XmlNamespaceManager nsMgr = new XmlNamespaceManager(document.NameTable);
// XPath 1.0 associates empty prefix with "null" namespace; must use non-empty prefix for default namespace.
// This will not work: nsMgr.AddNamespace("", "http://msh");
nsMgr.AddNamespace("msh", "http://msh");
nsMgr.AddNamespace("command", "http://schemas.microsoft.com/maml/dev/command/2004/10");
// Split the help item name into verb and noun
string verb = helpItemName.Split('-')[0];
string noun = helpItemName.Substring(helpItemName.IndexOf('-') + 1);
//Compose XPath query to select the appropriate node based on the verb, noun and id
string xpathQuery = "/msh:helpItems/msh:providerHelp/msh:CmdletHelpPaths/msh:CmdletHelpPath[@id='" + child + "' or @ID='" + child + "']/command:command/command:details[command:verb='" + verb + "' and command:noun='" + noun + "']";
// Execute the XPath query and if the command was found, return its MAML snippet
XmlNode result = null;
try
{
result = document.SelectSingleNode(xpathQuery, nsMgr);
}
catch(XPathException)
{
return String.Empty;
}
if (result != null)
{
return result.ParentNode.OuterXml;
}
return String.Empty;
}
#endregion
#region DriveCmdletProvider
/// <summary>
///
/// </summary>
/// <param name="drive"></param>
/// <returns></returns>
protected override PSDriveInfo NewDrive(PSDriveInfo drive)
{
if (drive == null)
{
return null;
}
if (String.IsNullOrEmpty(drive.Root) == false)
{
AssertError(helper.GetResourceMsgFromResourcetext("NewDriveRootDoesNotExist"), false);
return null;
}
return drive;
}
/// <summary>
/// Adds the required drive
/// </summary>
/// <returns></returns>
protected override Collection<PSDriveInfo> InitializeDefaultDrives()
{
Collection<PSDriveInfo> drives = new Collection<PSDriveInfo>();
drives.Add(new PSDriveInfo(WSManStringLiterals.rootpath, ProviderInfo, String.Empty,
helper.GetResourceMsgFromResourcetext("ConfigStorage"), null));
return drives;
}
/// <summary>
/// Removes the required drive
/// </summary>
/// <returns></returns>
protected override PSDriveInfo RemoveDrive(PSDriveInfo drive)
{
WSManHelper.ReleaseSessions();
return drive;
}
#endregion
#region ItemCmdletProvider
/// <summary>
/// Get a Child Name. This method is called from MakePath method.
/// This Method helps in getting the correct case of particular element in the provider path.
/// XML is case sensitive but Powershell is not.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
protected override string GetChildName(string path)
{
string result = String.Empty;
int separatorIndex = path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator);
string hostname = String.Empty;
if (separatorIndex == -1)
{
result = path;
hostname = path;
}
else
{
result = path.Substring(separatorIndex + 1);
hostname = GetHostName(path);
}
return GetCorrectCaseOfName(result, hostname, path);
}
/// <summary>
/// This method is provided by the Provider infrastructure. This method is called in all actions done
/// by the provider to get the resolved path. Internally Resolve-Path is called.
/// Since Root is empty for WsMan Provider the default path generated by Makepath is not correct.
/// So we have made the tweaks in this method to return the correct resolved path.
/// </summary>
/// <param name="parent"></param>
/// <param name="child"></param>
/// <returns></returns>
protected override string MakePath(string parent, string child)
{
if (child.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase))
{
child = child.Remove(child.LastIndexOf(WSManStringLiterals.DefaultPathSeparator));
}
//For Listeners only ... should remove Listener from listener\listener but not from listener_[Hashcode]
if (parent.Equals(WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase) && child.StartsWith(parent, StringComparison.OrdinalIgnoreCase))
{
if (!child.StartsWith(parent + "_", StringComparison.OrdinalIgnoreCase))
{
child = child.Remove(0, parent.Length);
}
}
string path = string.Empty;
string ChildName = string.Empty;
string CorrectCaseChildName = string.Empty;
if (parent.Length != 0)
{
path = parent + WSManStringLiterals.DefaultPathSeparator + child;
}
else
{
path = child;
}
if (path.Length != 0)
{
ChildName = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1);
CorrectCaseChildName = GetChildName(path);
}
if (ChildName.Equals(CorrectCaseChildName, StringComparison.OrdinalIgnoreCase))
{
if (child.Contains(WSManStringLiterals.DefaultPathSeparator.ToString()))
{
child = child.Substring(0, child.LastIndexOf(WSManStringLiterals.DefaultPathSeparator));
child = child + WSManStringLiterals.DefaultPathSeparator + CorrectCaseChildName;
}
else
{
child = CorrectCaseChildName;
}
}
String basepath = base.MakePath(parent, child);
return GetCorrectCaseOfPath(basepath);
}
/// <summary>
/// Checks whether the path is Valid.
/// eg. winrm/config/client
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
protected override bool IsValidPath(string path)
{
bool result = false;
result = CheckValidContainerOrPath(path);
return result;
}
/// <summary>
/// Check whether an Item Exist in the winrm configuration
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
protected override bool ItemExists(string path)
{
bool result = false;
result = CheckValidContainerOrPath(path);
return result;
}
/// <summary>
/// Checks whether the given path has got child items.
/// e.g: This is called by Provider infrastructure when we do a Remove-Item and prompts user
/// if child items are present.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
protected override bool HasChildItems(string path)
{
string childname = String.Empty;
string strPathCheck = String.Empty;
if (path.Length == 0 && String.IsNullOrEmpty(childname))
{
return true;
}
//if endswith '\', removes it.
if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase))
{
path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator));
}
if (path.Contains(WSManStringLiterals.DefaultPathSeparator.ToString()))
{
//Get the ChildName
childname = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1);
}
Dictionary<string, object> SessionObjCache = WSManHelper.GetSessionObjCache();
if (SessionObjCache.ContainsKey(path))
{
return true;
}
//Get the wsman host name to find the session object
string host = GetHostName(path);
//Chks the WinRM Service
if (IsPathLocalMachine(host))
{
if (!IsWSManServiceRunning())
{
WSManHelper.ThrowIfNotAdministrator();
StartWSManService(Force);
}
}
string WsManURI = NormalizePath(path, host);
lock(WSManHelper.AutoSession)
{
//Gets the session object from the cache.
object sessionobj;
SessionObjCache.TryGetValue(host, out sessionobj);
/*
WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Child Items.
* 1. Branch in to Listeners (winrm/config/listener)
* 2. Branch in to CertMapping (winrm/config/service/certmapping)
* 3. Branch in to Plugin (winrm/config/plugin) - Plugin is subdivided in Resources,Security & InitParams
* 4. Rest all the branches like Client, Shell(WinRS) ,Service
*/
// 1. Listener Checks
strPathCheck = host + WSManStringLiterals.DefaultPathSeparator;
if (WsManURI.Contains(WSManStringLiterals.containerListener))
{
XmlDocument xmlListeners = EnumerateResourceValue(sessionobj, WsManURI);
if (xmlListeners != null)
{
Hashtable KeyCache, ListenerObjCache;
ProcessListenerObjects(xmlListeners, out ListenerObjCache, out KeyCache);
if (ListenerObjCache.Count > 0)
{
return true;
}
}
}
// 2. Client Certificate Checks
else if (WsManURI.Contains(WSManStringLiterals.containerCertMapping))
{
XmlDocument xmlCertificates = EnumerateResourceValue(sessionobj, WsManURI);
Hashtable KeyCache, CertificatesObjCache;
if (xmlCertificates == null)
{
return true;
}
ProcessCertMappingObjects(xmlCertificates, out CertificatesObjCache, out KeyCache);
if (CertificatesObjCache.Count > 0)
{
return true;
}
}
// 3. Plugin and its internal structure Checks
else if (WsManURI.Contains(WSManStringLiterals.containerPlugin))
{
strPathCheck = strPathCheck + WSManStringLiterals.containerPlugin;
//Check for Plugin path
XmlDocument xmlPlugins = FindResourceValue(sessionobj, WsManURI, null);
string currentpluginname = string.Empty;
int PluginCount = GetPluginNames(xmlPlugins, out objPluginNames, out currentpluginname, path);
if (path.Equals(strPathCheck))
{
if (PluginCount > 0)
{
return true;
}
else
{
return false;
}
}
strPathCheck = strPathCheck + WSManStringLiterals.DefaultPathSeparator + currentpluginname;
if (path.EndsWith(strPathCheck, StringComparison.OrdinalIgnoreCase))
{
if (objPluginNames != null)
{
if (objPluginNames.Properties.Match(currentpluginname).Count > 0)
{
return true;
}
else
{
return false;
}
}
}
string filter = WsManURI + "?Name=" + currentpluginname;
XmlDocument CurrentPluginXML = GetResourceValue(sessionobj, filter, null);
ArrayList arrSecurities = null;
ArrayList arrResources = ProcessPluginResourceLevel(CurrentPluginXML, out arrSecurities);
ArrayList arrInitParams = ProcessPluginInitParamLevel(CurrentPluginXML);
strPathCheck = strPathCheck + WSManStringLiterals.DefaultPathSeparator;
if (path.EndsWith(strPathCheck + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase))
{
if (null != arrResources && arrResources.Count > 0)
{
return true;
}
}
if (path.EndsWith(strPathCheck + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase))
{
if (arrInitParams != null && arrInitParams.Count > 0)
{
return true;
}
}
if (path.EndsWith(strPathCheck + WSManStringLiterals.containerQuotasParameters, StringComparison.OrdinalIgnoreCase))
{
XmlNodeList nodeListForQuotas = CurrentPluginXML.GetElementsByTagName(WSManStringLiterals.containerQuotasParameters);
if (nodeListForQuotas.Count > 0)
{
XmlNode pluginQuotas = nodeListForQuotas[0];
return pluginQuotas.Attributes.Count > 0;
}
return false;
}
if (arrResources != null)
{
foreach (PSObject objresource in arrResources)
{
string sResourceDirName = objresource.Properties["ResourceDir"].Value.ToString();
if (path.Contains(sResourceDirName))
{
strPathCheck = strPathCheck + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator;
if (path.EndsWith(strPathCheck + sResourceDirName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
strPathCheck = strPathCheck + sResourceDirName + WSManStringLiterals.DefaultPathSeparator;
if (path.Contains(strPathCheck + WSManStringLiterals.containerSecurity))
{
if (path.EndsWith(strPathCheck + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase))
{
if (null != arrSecurities && arrSecurities.Count > 0)
{
return true;
}
}
strPathCheck = strPathCheck + WSManStringLiterals.containerSecurity + WSManStringLiterals.DefaultPathSeparator;
if (path.Contains(strPathCheck + WSManStringLiterals.containerSecurity + "_"))
{
if (null == arrSecurities)
{
return false;
}
foreach (PSObject security in arrSecurities)
{
string sSecurity = security.Properties["SecurityDIR"].Value.ToString();
if (path.EndsWith(sSecurity, StringComparison.OrdinalIgnoreCase))
return true;
}
}
}
}
}
}
}
else
// 4. All Other Item Checks
{
string getXml = this.GetResourceValueInXml(sessionobj, WsManURI, null);
XmlDocument xmlResourceValues = new XmlDocument();
xmlResourceValues.LoadXml(getXml.ToLowerInvariant());
XmlNodeList nodes = SearchXml(xmlResourceValues, childname, WsManURI, path, host);
if (nodes != null)
{
return IsItemContainer(nodes);
}
}
return false;
}
}
/// <summary>
/// This cmdlet is used to get a particular item.
/// cd wsman:\localhost\client> Get-Item .\Auth
/// </summary>
/// <param name="path"></param>
[SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")]
protected override void GetItem(string path)
{
string childname = string.Empty;
if (path.Length == 0 && String.IsNullOrEmpty(childname))
{
WriteItemObject(GetItemPSObjectWithTypeName(WSManStringLiterals.rootpath, WSManStringLiterals.ContainerChildValue, null, null, null, WsManElementObjectTypes.WSManConfigElement), WSManStringLiterals.rootpath, true);
return;
}
if (path.Contains(WSManStringLiterals.DefaultPathSeparator.ToString()))
{
//Get the ChildName
childname = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1);
}
else
{
childname = path;
}
Dictionary<string, object> SessionObjCache = WSManHelper.GetSessionObjCache();
if (childname.Equals(path, StringComparison.OrdinalIgnoreCase))
{
if (SessionObjCache.ContainsKey(childname))
{
WriteItemObject(GetItemPSObjectWithTypeName(childname, WSManStringLiterals.ContainerChildValue, null, null, "ComputerLevel", WsManElementObjectTypes.WSManConfigContainerElement), WSManStringLiterals.rootpath + WSManStringLiterals.DefaultPathSeparator + childname, true);
}
return;
}
path = path.Substring(0, path.LastIndexOf(childname, StringComparison.OrdinalIgnoreCase));
//Get the wsman host name to find the session object
string host = GetHostName(path);
string uri = NormalizePath(path, host);
lock(WSManHelper.AutoSession)
{
//Gets the session object from the cache.
object sessionobj;
SessionObjCache.TryGetValue(host, out sessionobj);
XmlDocument xmlResource = FindResourceValue(sessionobj, uri, null);
if (xmlResource == null) { return; }
//if endswith '\', removes it.
if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase))
{
path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator));
}
string strPathChk = host + WSManStringLiterals.DefaultPathSeparator;
if (path.Contains(strPathChk + WSManStringLiterals.containerListener))
{
GetItemListenerOrCertMapping(path, xmlResource, WSManStringLiterals.containerListener, childname, host);
}
else if (path.Contains(strPathChk + WSManStringLiterals.containerClientCertificate))
{
GetItemListenerOrCertMapping(path, xmlResource, WSManStringLiterals.containerClientCertificate, childname, host);
}
else if (path.Contains(strPathChk + WSManStringLiterals.containerPlugin))
{
string currentpluginname = string.Empty;
GetPluginNames(xmlResource, out objPluginNames, out currentpluginname, path);
if (path.EndsWith(strPathChk + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase))
{
try
{
WriteItemObject(GetItemPSObjectWithTypeName(objPluginNames.Properties[childname].Name, objPluginNames.Properties[childname].Value.ToString(), null, new string[] { "Name=" + objPluginNames.Properties[childname].Name }, null, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + childname, true);
}
catch (PSArgumentNullException) { return; }
catch (NullReferenceException) { return; }
}
else
{
strPathChk = strPathChk + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator;
string filter = uri + "?Name=" + currentpluginname;
XmlDocument CurrentPluginXML = GetResourceValue(sessionobj, filter, null);
if (null == CurrentPluginXML)
{
return;
}
PSObject objPluginlevel = ProcessPluginConfigurationLevel(CurrentPluginXML, true);
ArrayList arrSecurity = null;
ArrayList arrResources = ProcessPluginResourceLevel(CurrentPluginXML, out arrSecurity);
ArrayList arrInitParams = ProcessPluginInitParamLevel(CurrentPluginXML);
try
{
if (path.Contains(strPathChk + currentpluginname))
{
if (path.EndsWith(strPathChk + currentpluginname, StringComparison.OrdinalIgnoreCase))
{
if (!objPluginlevel.Properties[childname].Value.ToString().Equals(WSManStringLiterals.ContainerChildValue))
{
WriteItemObject(GetItemPSObjectWithTypeName(objPluginlevel.Properties[childname].Name, objPluginlevel.Properties[childname].TypeNameOfValue, objPluginlevel.Properties[childname].Value, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + objPluginlevel.Properties[childname].Name, false);
}
else
{
WriteItemObject(GetItemPSObjectWithTypeName(objPluginlevel.Properties[childname].Name, objPluginlevel.Properties[childname].Value.ToString(), null, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + objPluginlevel.Properties[childname].Name, true);
}
}
strPathChk = strPathChk + currentpluginname + WSManStringLiterals.DefaultPathSeparator;
if (path.Contains(strPathChk + WSManStringLiterals.containerResources))
{
if (null == arrResources)
{
return;
}
if (path.EndsWith(strPathChk + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase))
{
foreach (PSObject p in arrResources)
{
if (p.Properties["ResourceDir"].Value.ToString().Equals(childname))
{
WriteItemObject(GetItemPSObjectWithTypeName(childname, WSManStringLiterals.ContainerChildValue, null, new string[] { "ResourceURI=" + p.Properties["ResourceUri"].Value.ToString() }, null, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + childname, true);
}
}
return;
}
strPathChk = strPathChk + WSManStringLiterals.containerResources + WSManStringLiterals.DefaultPathSeparator;
int Sepindex = path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length);
string sResourceDirName = string.Empty;
if (Sepindex == -1)
{
sResourceDirName = path.Substring(strPathChk.Length);
}
else
{
sResourceDirName = path.Substring(strPathChk.Length, path.IndexOf(WSManStringLiterals.DefaultPathSeparator, strPathChk.Length) - (strPathChk.Length));
}
if (path.Contains(strPathChk + sResourceDirName))
{
if (path.EndsWith(strPathChk + sResourceDirName, StringComparison.OrdinalIgnoreCase))
{
foreach (PSObject p in arrResources)
{
if (sResourceDirName.Equals(p.Properties["ResourceDir"].Value.ToString(), StringComparison.OrdinalIgnoreCase))
{
p.Properties.Remove("ResourceDir");
if (p.Properties[childname].Value.ToString().Equals(WSManStringLiterals.ContainerChildValue))
{
WriteItemObject(GetItemPSObjectWithTypeName(p.Properties[childname].Name, p.Properties[childname].Value.ToString(), null, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + p.Properties[childname].Name, true);
}
else
{
WriteItemObject(GetItemPSObjectWithTypeName(p.Properties[childname].Name, p.Properties[childname].TypeNameOfValue, p.Properties[childname].Value, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + p.Properties[childname].Name, false);
}
break;
}
}
return;
}
strPathChk = strPathChk + sResourceDirName + WSManStringLiterals.DefaultPathSeparator;
if (path.Contains(strPathChk + WSManStringLiterals.containerSecurity))
{
if (null == arrSecurity)
{
return;
}
foreach (PSObject p in arrSecurity)
{
if (path.EndsWith(WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase))
{
WriteItemObject(GetItemPSObjectWithTypeName(p.Properties["SecurityDIR"].Value.ToString(), WSManStringLiterals.ContainerChildValue, null, new string[] { "Uri=" + p.Properties["Uri"].Value.ToString() }, null, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + p.Properties["SecurityDIR"].Value.ToString(), true);
}
else
{
string sSecurityDirName = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1, path.Length - (path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1));
if (sSecurityDirName.Equals(p.Properties["SecurityDIR"].Value.ToString()))
{
p.Properties.Remove("SecurityDIR");
WriteItemObject(GetItemPSObjectWithTypeName(p.Properties[childname].Name, p.Properties[childname].TypeNameOfValue, p.Properties[childname].Value, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + p.Properties[childname].Name, false);
break;
}
}
}
return;
}
}
}
else if (path.EndsWith(host + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator + currentpluginname + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase))
{
if (null != arrInitParams)
{
foreach (PSObject p in arrInitParams)
{
if (p.Properties.Match(childname, PSMemberTypes.NoteProperty).Count > 0)
WriteItemObject(GetItemPSObjectWithTypeName(p.Properties[childname].Name, p.Properties[childname].TypeNameOfValue, p.Properties[childname].Value, null, "InitParams", WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + p.Properties[childname].Name, false);
}
}
}
else if (path.EndsWith(WSManStringLiterals.containerQuotasParameters, StringComparison.OrdinalIgnoreCase))
{
// Get the Quotas element from the config XML.
XmlNodeList nodeListForQuotas = CurrentPluginXML.GetElementsByTagName(WSManStringLiterals.containerQuotasParameters);
if (nodeListForQuotas.Count > 0)
{
XmlNode pluginQuotas = nodeListForQuotas[0];
foreach (XmlAttribute attrOfQuotas in pluginQuotas.Attributes)
{
if (childname.Equals(attrOfQuotas.Name, StringComparison.OrdinalIgnoreCase))
{
PSObject objectToAdd =
GetItemPSObjectWithTypeName(
attrOfQuotas.Name,
attrOfQuotas.Value.GetType().ToString(),
attrOfQuotas.Value,
null,
null,
WsManElementObjectTypes.WSManConfigLeafElement);
String pathToAdd =
String.Format(
CultureInfo.InvariantCulture,
"{0}{1}{2}",
path,
WSManStringLiterals.DefaultPathSeparator,
attrOfQuotas.Name);
WriteItemObject(objectToAdd, pathToAdd, false);
break;
}
}
}
}
}
}
catch (PSArgumentNullException) { return; }
catch (NullReferenceException) { return; }
}
}
else
{
try
{
PSObject mshObject = null;
if (!uri.Equals(WinrmRootName[0].ToString(), StringComparison.OrdinalIgnoreCase))
{
foreach (XmlNode innerResourceNodes in xmlResource.ChildNodes)
{
mshObject = ConvertToPSObject(innerResourceNodes);
}
}
else
{
mshObject = BuildHostLevelPSObjectArrayList(sessionobj, uri, false);
}
if (mshObject != null)
{
if (mshObject.Properties[childname].Value.ToString().Equals(WSManStringLiterals.ContainerChildValue))
{
WriteItemObject(GetItemPSObjectWithTypeName(mshObject.Properties[childname].Name, mshObject.Properties[childname].Value.ToString(), null, null, null, WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + mshObject.Properties[childname].Name, true);
}
else
{
WriteItemObject(
GetItemPSObjectWithTypeName(
mshObject.Properties[childname].Name,
mshObject.Properties[childname].TypeNameOfValue,
mshObject.Properties[childname].Value,
null, null,
WsManElementObjectTypes.WSManConfigLeafElement,
mshObject),
path + WSManStringLiterals.DefaultPathSeparator + mshObject.Properties[childname].Name,
false);
}
}
}
catch (PSArgumentNullException) { return;/*Leaving this known exception for no value found. Not Throwing error.*/}
catch (NullReferenceException) { return; /*Leaving this known exception for no value found. Not Throwing error.*/}
}
}
}
/// <summary>
/// This cmdlet is used to set the value of a particular item.
/// cd wsman:\localhost\client> Set-Item .\TrustedHosts -value "*"
/// This has one dynamic parameter. It is used with TrustedHost only.
/// The parameter is -Concatenate.
/// </summary>
/// <param name="path"></param>
/// <param name="value"></param>
[SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")]
protected override void SetItem(string path, object value)
{
if (null == value)
{
throw new ArgumentException(helper.GetResourceMsgFromResourcetext("value"));
}
string ChildName = string.Empty;
if (path.Length == 0 && String.IsNullOrEmpty(ChildName))
{
AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false);
return;
}
if (path.Contains(WSManStringLiterals.DefaultPathSeparator.ToString()))
{
//Get the ChildName
ChildName = path.Substring(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator) + 1);
}
else
{
ChildName = path;
}
if (ChildName.Equals(path, StringComparison.OrdinalIgnoreCase))
{
AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false);
return;
}
if (!this.clearItemIsCalled)
{
value = this.ValidateAndGetUserObject(ChildName, value);
// The value will be Null only if the object provided by User is not of accepted type.
// As of now, this can only happen in case of RunAsUserName and RunAsPassword
if (value == null)
{
return;
}
}
else
{
// If validation is not required, that means Clear-Item cmdlet is called.
// Clear-Item is not allowed on RunAsPassword, Admin should call Clear-Item RunAsUser
// if he intends to disable RunAs on the Plugin.
if(String.Equals(ChildName, WSManStringLiterals.ConfigRunAsPasswordName, StringComparison.OrdinalIgnoreCase))
{
AssertError(helper.GetResourceMsgFromResourcetext("ClearItemOnRunAsPassword"), false);
return;
}
}
string whatIfMessage = String.Format(CultureInfo.CurrentUICulture, helper.GetResourceMsgFromResourcetext("SetItemWhatIfAndConfirmText"), path, value);
if (!ShouldProcess(whatIfMessage, "", ""))
{
return;
}
path = path.Substring(0, path.LastIndexOf(ChildName, StringComparison.OrdinalIgnoreCase));
//Get the wsman host name to find the session object
string host = GetHostName(path);
string uri = NormalizePath(path, host);
//Chk for Winrm Service
if (IsPathLocalMachine(host))
{
if (!IsWSManServiceRunning())
{
WSManHelper.ThrowIfNotAdministrator();
StartWSManService(this.Force);
}
}
bool settingPickedUpDynamically = false;
lock(WSManHelper.AutoSession)
{
//Gets the session object from the cache.
object sessionobj;
Dictionary<string, object> SessionObjCache = WSManHelper.GetSessionObjCache();
SessionObjCache.TryGetValue(host, out sessionobj);
List<String> warningMessage = new List<string>();
//if endswith '\', removes it.
if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase))
{
path = path.Remove(path.LastIndexOf(WSManStringLiterals.DefaultPathSeparator));
}
string strPathChk = host + WSManStringLiterals.DefaultPathSeparator;
if (path.Contains(strPathChk + WSManStringLiterals.containerListener))
{
SetItemListenerOrClientCertificate(sessionobj, uri, PKeyListener, ChildName, value, path, WSManStringLiterals.containerListener, host);
}
else if (path.Contains(strPathChk + WSManStringLiterals.containerClientCertificate))
{
SetItemListenerOrClientCertificate(sessionobj, uri, PKeyCertMapping, ChildName, value, path, WSManStringLiterals.containerClientCertificate, host);
}
else if (path.Contains(strPathChk + WSManStringLiterals.containerPlugin))
{
if (path.EndsWith(strPathChk + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase))
{
AssertError(helper.GetResourceMsgFromResourcetext("SetItemNotSupported"), false);
}
try
{
XmlDocument xmlPlugins = FindResourceValue(sessionobj, uri, null);
string currentpluginname = string.Empty;
GetPluginNames(xmlPlugins, out objPluginNames, out currentpluginname, path);
if (String.IsNullOrEmpty(currentpluginname))
{
if (!this.clearItemIsCalled)
{
// Don't need an error if ClearItem is called.
AssertError(helper.GetResourceMsgFromResourcetext("ItemDoesNotExist"), false);
}
return;
}
string filter = uri + "?Name=" + currentpluginname;
CurrentConfigurations pluginConfiguration = new CurrentConfigurations((IWSManSession)sessionobj);
string pluginXML = this.GetResourceValueInXml((IWSManSession)sessionobj, filter, null);
pluginConfiguration.RefreshCurrentConfiguration(pluginXML);
XmlDocument CurrentPluginXML = pluginConfiguration.RootDocument;
ArrayList arrSecurity = null;
ArrayList arrResources = ProcessPluginResourceLevel(CurrentPluginXML, out arrSecurity);
ArrayList arrInitParams = ProcessPluginInitParamLevel(CurrentPluginXML);
try
{
// Remove XML:LANG attribute if present.
// If not present ignore the exception.
pluginConfiguration.RemoveOneConfiguration("./attribute::xml:lang");
}
catch (ArgumentException)