File size: 52,601 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
using System.Text;

using Microsoft.PowerShell.Commands;
using Microsoft.Win32;

using Dbg = System.Management.Automation.Diagnostics;
using Regex = System.Text.RegularExpressions.Regex;

namespace System.Management.Automation
{
    internal static class RegistryStrings
    {
        /// <summary>
        /// Root key path under HKLM.
        /// </summary>
        internal const string MonadRootKeyPath = "Software\\Microsoft\\PowerShell";

        /// <summary>
        /// Root key name.
        /// </summary>
        internal const string MonadRootKeyName = "PowerShell";

        /// <summary>
        /// Key for monad engine.
        /// </summary>
        internal const string MonadEngineKey = "PowerShellEngine";

        // Name for various values under PSEngine
        internal const string MonadEngine_ApplicationBase = "ApplicationBase";
        internal const string MonadEngine_ConsoleHostAssemblyName = "ConsoleHostAssemblyName";
        internal const string MonadEngine_ConsoleHostModuleName = "ConsoleHostModuleName";
        internal const string MonadEngine_RuntimeVersion = "RuntimeVersion";
        internal const string MonadEngine_MonadVersion = "PowerShellVersion";

        /// <summary>
        /// Key under which all the mshsnapin live.
        /// </summary>
        internal const string MshSnapinKey = "PowerShellSnapIns";

        // Name of various values for each mshsnapin
        internal const string MshSnapin_ApplicationBase = "ApplicationBase";
        internal const string MshSnapin_AssemblyName = "AssemblyName";
        internal const string MshSnapin_ModuleName = "ModuleName";
        internal const string MshSnapin_MonadVersion = "PowerShellVersion";
        internal const string MshSnapin_BuiltInTypes = "Types";
        internal const string MshSnapin_BuiltInFormats = "Formats";
        internal const string MshSnapin_Description = "Description";
        internal const string MshSnapin_Version = "Version";
        internal const string MshSnapin_Vendor = "Vendor";
        internal const string MshSnapin_DescriptionResource = "DescriptionIndirect";
        internal const string MshSnapin_VendorResource = "VendorIndirect";
        internal const string MshSnapin_LogPipelineExecutionDetails = "LogPipelineExecutionDetails";

        // Name of default mshsnapins
        internal const string CoreMshSnapinName = "Microsoft.PowerShell.Core";
        internal const string HostMshSnapinName = "Microsoft.PowerShell.Host";
        internal const string ManagementMshSnapinName = "Microsoft.PowerShell.Management";
        internal const string SecurityMshSnapinName = "Microsoft.PowerShell.Security";
        internal const string UtilityMshSnapinName = "Microsoft.PowerShell.Utility";
    }

    /// <summary>
    /// Contains information about a PSSnapin.
    /// </summary>
    public class PSSnapInInfo
    {
        internal PSSnapInInfo
        (
            string name,
            bool isDefault,
            string applicationBase,
            string assemblyName,
            string moduleName,
            Version psVersion,
            Version version,
            Collection<string> types,
            Collection<string> formats,
            string descriptionFallback,
            string vendorFallback
        )
        {
            if (string.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(name));
            }

            if (string.IsNullOrEmpty(applicationBase))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(applicationBase));
            }

            if (string.IsNullOrEmpty(assemblyName))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(assemblyName));
            }

            if (string.IsNullOrEmpty(moduleName))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(moduleName));
            }

            if (psVersion == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(psVersion));
            }

            if (version == null)
            {
                version = new Version("0.0");
            }

            types ??= new Collection<string>();

            formats ??= new Collection<string>();

            descriptionFallback ??= string.Empty;

            vendorFallback ??= string.Empty;

            Name = name;
            IsDefault = isDefault;
            ApplicationBase = applicationBase;
            AssemblyName = assemblyName;
            ModuleName = moduleName;
            PSVersion = psVersion;
            Version = version;
            Types = types;
            Formats = formats;
            _descriptionFallback = descriptionFallback;
            _vendorFallback = vendorFallback;
        }

        internal PSSnapInInfo
        (
            string name,
            bool isDefault,
            string applicationBase,
            string assemblyName,
            string moduleName,
            Version psVersion,
            Version version,
            Collection<string> types,
            Collection<string> formats,
            string description,
            string descriptionFallback,
            string vendor,
            string vendorFallback
        )
        : this(name, isDefault, applicationBase, assemblyName, moduleName, psVersion, version, types, formats, descriptionFallback, vendorFallback)
        {
            _description = description;
            _vendor = vendor;
        }

        internal PSSnapInInfo
        (
            string name,
            bool isDefault,
            string applicationBase,
            string assemblyName,
            string moduleName,
            Version psVersion,
            Version version,
            Collection<string> types,
            Collection<string> formats,
            string description,
            string descriptionFallback,
            string descriptionIndirect,
            string vendor,
            string vendorFallback,
            string vendorIndirect
        ) : this(name, isDefault, applicationBase, assemblyName, moduleName, psVersion, version, types, formats, description, descriptionFallback, vendor, vendorFallback)
        {
            // add descriptionIndirect and vendorIndirect only if the mshsnapin is a default mshsnapin
            if (isDefault)
            {
                _descriptionIndirect = descriptionIndirect;
                _vendorIndirect = vendorIndirect;
            }
        }

        /// <summary>
        /// Unique Name of the PSSnapin.
        /// </summary>
        public string Name { get; }

        /// <summary>
        /// Is this PSSnapin default PSSnapin.
        /// </summary>
        public bool IsDefault { get; }

        /// <summary>
        /// Returns applicationbase for PSSnapin.
        /// </summary>
        public string ApplicationBase { get; }

        /// <summary>
        /// Strong name of PSSnapin assembly.
        /// </summary>
        public string AssemblyName { get; }

        /// <summary>
        /// Name of PSSnapIn module.
        /// </summary>
        public string ModuleName { get; }

        internal string AbsoluteModulePath
        {
            get
            {
                if (string.IsNullOrEmpty(ModuleName) || Path.IsPathRooted(ModuleName))
                {
                    return ModuleName;
                }
                else if (!File.Exists(Path.Combine(ApplicationBase, ModuleName)))
                {
                    return Path.GetFileNameWithoutExtension(ModuleName);
                }

                return Path.Combine(ApplicationBase, ModuleName);
            }
        }

        /// <summary>
        /// PowerShell version used by PSSnapin.
        /// </summary>
        public Version PSVersion { get; }

        /// <summary>
        /// Version of PSSnapin.
        /// </summary>
        public Version Version { get; }

        /// <summary>
        /// Collection of file names containing types information for PSSnapIn.
        /// </summary>
        public Collection<string> Types { get; }

        /// <summary>
        /// Collection of file names containing format information for PSSnapIn.
        /// </summary>
        public Collection<string> Formats { get; }

        private readonly string _descriptionIndirect;
        private readonly string _descriptionFallback = string.Empty;
        private string _description;
        /// <summary>
        /// Description of PSSnapin.
        /// </summary>
        public string Description
        {
            get
            {
                if (_description == null)
                {
                    LoadIndirectResources();
                }

                return _description;
            }
        }

        private readonly string _vendorIndirect;
        private readonly string _vendorFallback = string.Empty;
        private string _vendor;
        /// <summary>
        /// Vendor of PSSnapin.
        /// </summary>
        public string Vendor
        {
            get
            {
                if (_vendor == null)
                {
                    LoadIndirectResources();
                }

                return _vendor;
            }
        }

        /// <summary>
        /// Get/set whether to log Pipeline Execution Detail events.
        /// </summary>
        public bool LogPipelineExecutionDetails { get; set; } = false;

        /// <summary>
        /// Overrides ToString.
        /// </summary>
        /// <returns>
        /// Name of the PSSnapIn
        /// </returns>
        public override string ToString()
        {
            return Name;
        }

        internal RegistryKey MshSnapinKey
        {
            get
            {
                RegistryKey mshsnapinKey = null;

                try
                {
                    mshsnapinKey = PSSnapInReader.GetMshSnapinKey(Name, PSVersion.Major.ToString(CultureInfo.InvariantCulture));
                }
                catch (ArgumentException)
                {
                }
                catch (SecurityException)
                {
                }
                catch (System.IO.IOException)
                {
                }

                return mshsnapinKey;
            }
        }

        internal void LoadIndirectResources()
        {
            using (RegistryStringResourceIndirect resourceReader = RegistryStringResourceIndirect.GetResourceIndirectReader())
            {
                LoadIndirectResources(resourceReader);
            }
        }

        internal void LoadIndirectResources(RegistryStringResourceIndirect resourceReader)
        {
            if (IsDefault)
            {
                // For default mshsnapins..resource indirects are hardcoded..
                // so dont read from the registry
                _description = resourceReader.GetResourceStringIndirect(
                    AssemblyName,
                    ModuleName,
                    _descriptionIndirect);

                _vendor = resourceReader.GetResourceStringIndirect(
                    AssemblyName,
                    ModuleName,
                    _vendorIndirect);
            }
            else
            {
                RegistryKey mshsnapinKey = MshSnapinKey;
                if (mshsnapinKey != null)
                {
                    _description =
                        resourceReader.GetResourceStringIndirect(
                            mshsnapinKey,
                            RegistryStrings.MshSnapin_DescriptionResource,
                            AssemblyName,
                            ModuleName);

                    _vendor =
                        resourceReader.GetResourceStringIndirect(
                            mshsnapinKey,
                            RegistryStrings.MshSnapin_VendorResource,
                            AssemblyName,
                            ModuleName);
                }
            }

            if (string.IsNullOrEmpty(_description))
            {
                _description = _descriptionFallback;
            }

            if (string.IsNullOrEmpty(_vendor))
            {
                _vendor = _vendorFallback;
            }
        }

        internal PSSnapInInfo Clone()
        {
            PSSnapInInfo cloned = new PSSnapInInfo(
                Name,
                IsDefault,
                ApplicationBase,
                AssemblyName,
                ModuleName,
                PSVersion,
                Version,
                new Collection<string>(Types),
                new Collection<string>(Formats),
                _description,
                _descriptionFallback,
                _descriptionIndirect,
                 _vendor,
                 _vendorFallback,
                 _vendorIndirect);

            return cloned;
        }

        /// <summary>
        /// Returns true if the PSSnapIn Id is valid. A PSSnapIn is valid
        /// if-and-only-if it contains only "Alpha Numeric","-","_","."
        /// characters.
        /// </summary>
        /// <param name="psSnapinId">PSSnapIn Id to validate.</param>
        internal static bool IsPSSnapinIdValid(string psSnapinId)
        {
            if (string.IsNullOrEmpty(psSnapinId))
            {
                return false;
            }

            return Regex.IsMatch(psSnapinId, "^[A-Za-z0-9-_\x2E]*$");
        }

        /// <summary>
        /// Validates the PSSnapIn Id. A PSSnapIn is valid if-and-only-if it
        /// contains only "Alpha Numeric","-","_","." characters.
        /// </summary>
        /// <param name="psSnapinId">PSSnapIn Id to validate.</param>
        /// <exception cref="PSArgumentException">
        /// 1. Specified PSSnapIn is not valid
        /// </exception>
        internal static void VerifyPSSnapInFormatThrowIfError(string psSnapinId)
        {
            // PSSnapIn do not conform to the naming convention..so throw
            // argument exception
            if (!IsPSSnapinIdValid(psSnapinId))
            {
                throw PSTraceSource.NewArgumentException(nameof(psSnapinId),
                    MshSnapInCmdletResources.InvalidPSSnapInName,
                    psSnapinId);
            }

            // Valid SnapId..Just return
            return;
        }
    }

    /// <summary>
    /// Internal class to read information about a mshsnapin.
    /// </summary>
    internal static class PSSnapInReader
    {
        /// <summary>
        /// Reads all registered mshsnapin for all monad versions.
        /// </summary>
        /// <returns>
        /// A collection of PSSnapInInfo objects
        /// </returns>
        /// <exception cref="SecurityException">
        /// User doesn't have access to monad/mshsnapin registration information
        /// </exception>
        /// <exception cref="ArgumentException">
        /// Monad key is not installed
        /// </exception>
        internal static Collection<PSSnapInInfo> ReadAll()
        {
            Collection<PSSnapInInfo> allMshSnapins = new Collection<PSSnapInInfo>();
            RegistryKey monadRootKey = GetMonadRootKey();

            string[] versions = monadRootKey.GetSubKeyNames();
            if (versions == null)
            {
                return allMshSnapins;
            }

            // PS V3 snapin information is stored under 1 registry key..
            // so no need to iterate over twice.
            Collection<string> filteredVersions = new Collection<string>();
            foreach (string version in versions)
            {
                string temp = PSVersionInfo.GetRegistryVersionKeyForSnapinDiscovery(version);
                if (string.IsNullOrEmpty(temp))
                {
                    temp = version;
                }

                if (!filteredVersions.Contains(temp))
                {
                    filteredVersions.Add(temp);
                }
            }

            foreach (string version in filteredVersions)
            {
                if (string.IsNullOrEmpty(version))
                {
                    continue;
                }
                // found a key which is not version
                if (!MeetsVersionFormat(version))
                {
                    continue;
                }

                Collection<PSSnapInInfo> oneVersionMshSnapins = null;
                try
                {
                    oneVersionMshSnapins = ReadAll(monadRootKey, version);
                }
                // If we cannot get information for one version, continue with other
                // versions
                catch (SecurityException)
                {
                }
                catch (ArgumentException)
                {
                }

                if (oneVersionMshSnapins != null)
                {
                    foreach (PSSnapInInfo info in oneVersionMshSnapins)
                    {
                        allMshSnapins.Add(info);
                    }
                }
            }

            return allMshSnapins;
        }

        /// <summary>
        /// Version should be integer (1, 2, 3 etc)
        /// </summary>
        /// <param name="version"></param>
        /// <returns></returns>
        private
        static
        bool MeetsVersionFormat(string version)
        {
            bool r = true;
            try
            {
                LanguagePrimitives.ConvertTo(version, typeof(int), CultureInfo.InvariantCulture);
            }
            catch (PSInvalidCastException)
            {
                r = false;
            }

            return r;
        }

        /// <summary>
        /// Reads all registered mshsnapin for specified psVersion.
        /// </summary>
        /// <returns>
        /// A collection of PSSnapInInfo objects
        /// </returns>
        /// <exception cref="SecurityException">
        /// User doesn't have permission to read MonadRoot or Version
        /// </exception>
        /// <exception cref="ArgumentException">
        /// MonadRoot or Version key doesn't exist.
        /// </exception>
        internal static Collection<PSSnapInInfo> ReadAll(string psVersion)
        {
            if (string.IsNullOrEmpty(psVersion))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(psVersion));
            }

            RegistryKey monadRootKey = GetMonadRootKey();
            return ReadAll(monadRootKey, psVersion);
        }

        /// <summary>
        /// Reads all the mshsnapins for a given psVersion.
        /// </summary>
        /// <exception cref="SecurityException">
        /// The User doesn't have required permission to read the registry key for this version.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// Specified version doesn't exist.
        /// </exception>
        /// <exception cref="SecurityException">
        /// User doesn't have permission to read specified version
        /// </exception>
        private static Collection<PSSnapInInfo> ReadAll(RegistryKey monadRootKey, string psVersion)
        {
            Dbg.Assert(monadRootKey != null, "caller should validate the information");
            Dbg.Assert(!string.IsNullOrEmpty(psVersion), "caller should validate the information");

            Collection<PSSnapInInfo> mshsnapins = new Collection<PSSnapInInfo>();
            RegistryKey versionRoot = GetVersionRootKey(monadRootKey, psVersion);
            RegistryKey mshsnapinRoot = GetMshSnapinRootKey(versionRoot, psVersion);

            // get name of all mshsnapin for this version
            string[] mshsnapinIds = mshsnapinRoot.GetSubKeyNames();

            foreach (string id in mshsnapinIds)
            {
                if (string.IsNullOrEmpty(id))
                {
                    continue;
                }

                try
                {
                    mshsnapins.Add(ReadOne(mshsnapinRoot, id));
                }
                // If we cannot read some mshsnapins, we should continue
                catch (SecurityException)
                {
                }
                catch (ArgumentException)
                {
                }
            }

            return mshsnapins;
        }

        /// <summary>
        /// Read mshsnapin for specified mshsnapinId and psVersion.
        /// </summary>
        /// <returns>
        /// MshSnapin info object
        /// </returns>
        /// <exception cref="SecurityException">
        /// The user does not have the permissions required to read the
        /// registry key for one of the following:
        /// 1) Monad
        /// 2) PSVersion
        /// 3) MshSnapinId
        /// </exception>
        /// <exception cref="ArgumentException">
        /// 1) Monad key is not present
        /// 2) VersionKey is not present
        /// 3) MshSnapin key is not present
        /// 4) MshSnapin key is not valid
        /// </exception>
        internal static PSSnapInInfo Read(string psVersion, string mshsnapinId)
        {
            if (string.IsNullOrEmpty(psVersion))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(psVersion));
            }

            if (string.IsNullOrEmpty(mshsnapinId))
            {
                throw PSTraceSource.NewArgumentNullException(nameof(mshsnapinId));
            }
            // PSSnapIn Reader wont service invalid mshsnapins
            // Monad has specific restrictions on the mshsnapinid like
            // mshsnapinid should be A-Za-z0-9.-_ etc.
            PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(mshsnapinId);

            RegistryKey rootKey = GetMonadRootKey();
            RegistryKey versionRoot = GetVersionRootKey(rootKey, psVersion);
            RegistryKey mshsnapinRoot = GetMshSnapinRootKey(versionRoot, psVersion);

            return ReadOne(mshsnapinRoot, mshsnapinId);
        }

        /// <summary>
        /// Reads the mshsnapin info for a specific key under specific monad version.
        /// </summary>
        /// <remarks>
        /// ReadOne will never create a default PSSnapInInfo object.
        /// </remarks>
        /// <exception cref="SecurityException">
        /// The user does not have the permissions required to read the
        /// registry key for specified mshsnapin.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// 1) Specified mshsnapin is not installed.
        /// 2) Specified mshsnapin is not correctly installed.
        /// </exception>
        private static PSSnapInInfo ReadOne(RegistryKey mshSnapInRoot, string mshsnapinId)
        {
            Dbg.Assert(!string.IsNullOrEmpty(mshsnapinId), "caller should validate the parameter");
            Dbg.Assert(mshSnapInRoot != null, "caller should validate the parameter");

            RegistryKey mshsnapinKey;
            mshsnapinKey = mshSnapInRoot.OpenSubKey(mshsnapinId);
            if (mshsnapinKey == null)
            {
                s_mshsnapinTracer.TraceError("Error opening registry key {0}\\{1}.", mshSnapInRoot.Name, mshsnapinId);
                throw PSTraceSource.NewArgumentException(nameof(mshsnapinId), MshSnapinInfo.MshSnapinDoesNotExist, mshsnapinId);
            }

            string applicationBase = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_ApplicationBase, true);
            string assemblyName = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_AssemblyName, true);
            string moduleName = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_ModuleName, true);
            Version monadVersion = ReadVersionValue(mshsnapinKey, RegistryStrings.MshSnapin_MonadVersion, true);
            Version version = ReadVersionValue(mshsnapinKey, RegistryStrings.MshSnapin_Version, false);

            string description = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_Description, false);
            if (description == null)
            {
                s_mshsnapinTracer.WriteLine("No description is specified for mshsnapin {0}. Using empty string for description.", mshsnapinId);
                description = string.Empty;
            }

            string vendor = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_Vendor, false);
            if (vendor == null)
            {
                s_mshsnapinTracer.WriteLine("No vendor is specified for mshsnapin {0}. Using empty string for description.", mshsnapinId);
                vendor = string.Empty;
            }

            bool logPipelineExecutionDetails = false;
            string logPipelineExecutionDetailsStr = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_LogPipelineExecutionDetails, false);
            if (!string.IsNullOrEmpty(logPipelineExecutionDetailsStr))
            {
                if (string.Equals("1", logPipelineExecutionDetailsStr, StringComparison.OrdinalIgnoreCase))
                    logPipelineExecutionDetails = true;
            }

            Collection<string> types = ReadMultiStringValue(mshsnapinKey, RegistryStrings.MshSnapin_BuiltInTypes, false);
            Collection<string> formats = ReadMultiStringValue(mshsnapinKey, RegistryStrings.MshSnapin_BuiltInFormats, false);

            s_mshsnapinTracer.WriteLine("Successfully read registry values for mshsnapin {0}. Constructing PSSnapInInfo object.", mshsnapinId);
            PSSnapInInfo mshSnapinInfo = new PSSnapInInfo(mshsnapinId, false, applicationBase, assemblyName, moduleName, monadVersion, version, types, formats, description, vendor);
            mshSnapinInfo.LogPipelineExecutionDetails = logPipelineExecutionDetails;

            return mshSnapinInfo;
        }

        /// <summary>
        /// Gets multistring value for name.
        /// </summary>
        /// <param name="mshsnapinKey"></param>
        /// <param name="name"></param>
        /// <param name="mandatory"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">
        /// if value is not present and mandatory is true
        /// </exception>
        private static Collection<string> ReadMultiStringValue(RegistryKey mshsnapinKey, string name, bool mandatory)
        {
            object value = mshsnapinKey.GetValue(name);
            if (value == null)
            {
                // If this key should be present..throw error
                if (mandatory)
                {
                    s_mshsnapinTracer.TraceError("Mandatory property {0} not specified for registry key {1}",
                        name, mshsnapinKey.Name);
                    throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.MandatoryValueNotPresent, name, mshsnapinKey.Name);
                }
                else
                {
                    return null;
                }
            }

            // value cannot be null here...
            string[] msv = value as string[];

            if (msv == null)
            {
                // Check if the value is in string format
                if (value is string singleValue)
                {
                    msv = new string[1];
                    msv[0] = singleValue;
                }
            }

            if (msv == null)
            {
                if (mandatory)
                {
                    s_mshsnapinTracer.TraceError("Cannot get string/multi-string value for mandatory property {0} in registry key {1}",
                        name, mshsnapinKey.Name);
                    throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.MandatoryValueNotInCorrectFormatMultiString, name, mshsnapinKey.Name);
                }
                else
                {
                    return null;
                }
            }

            s_mshsnapinTracer.WriteLine("Successfully read property {0} from {1}",
                name, mshsnapinKey.Name);
            return new Collection<string>(msv);
        }

        /// <summary>
        /// Get the value for name.
        /// </summary>
        /// <param name="mshsnapinKey"></param>
        /// <param name="name"></param>
        /// <param name="mandatory"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">
        /// if no value is available and mandatory is true.
        /// </exception>
        internal static string ReadStringValue(RegistryKey mshsnapinKey, string name, bool mandatory)
        {
            Dbg.Assert(!string.IsNullOrEmpty(name), "caller should validate the parameter");
            Dbg.Assert(mshsnapinKey != null, "Caller should validate the parameter");

            object value = mshsnapinKey.GetValue(name);
            if (value == null && mandatory)
            {
                s_mshsnapinTracer.TraceError("Mandatory property {0} not specified for registry key {1}",
                        name, mshsnapinKey.Name);
                throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.MandatoryValueNotPresent, name, mshsnapinKey.Name);
            }

            string s = value as string;
            if (string.IsNullOrEmpty(s) && mandatory)
            {
                s_mshsnapinTracer.TraceError("Value is null or empty for mandatory property {0} in {1}",
                        name, mshsnapinKey.Name);
                throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.MandatoryValueNotInCorrectFormat, name, mshsnapinKey.Name);
            }

            s_mshsnapinTracer.WriteLine("Successfully read value {0} for property {1} from {2}",
                s, name, mshsnapinKey.Name);
            return s;
        }

        internal static Version ReadVersionValue(RegistryKey mshsnapinKey, string name, bool mandatory)
        {
            string temp = ReadStringValue(mshsnapinKey, name, mandatory);
            if (temp == null)
            {
                s_mshsnapinTracer.TraceError("Cannot read value for property {0} in registry key {1}",
                    name, mshsnapinKey.ToString());
                Dbg.Assert(!mandatory, "mandatory is true, ReadStringValue should have thrown exception");
                return null;
            }

            Version v;
            try
            {
                v = new Version(temp);
            }
            catch (ArgumentOutOfRangeException)
            {
                s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp);
                throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name);
            }
            catch (ArgumentException)
            {
                s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp);
                throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name);
            }
            catch (OverflowException)
            {
                s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp);
                throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name);
            }
            catch (FormatException)
            {
                s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp);
                throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name);
            }

            s_mshsnapinTracer.WriteLine("Successfully converted string {0} to version format.", v);
            return v;
        }

        internal static void ReadRegistryInfo(out Version assemblyVersion, out string publicKeyToken, out string culture, out string applicationBase, out Version psVersion)
        {
            applicationBase = Utils.DefaultPowerShellAppBase;
            Dbg.Assert(
                !string.IsNullOrEmpty(applicationBase),
                string.Create(CultureInfo.CurrentCulture, $"{RegistryStrings.MonadEngine_ApplicationBase} is empty or null"));

            // Get the PSVersion from Utils..this is hardcoded
            psVersion = PSVersionInfo.PSVersion;
            Dbg.Assert(
                psVersion != null,
                string.Create(CultureInfo.CurrentCulture, $"{RegistryStrings.MonadEngine_MonadVersion} is null"));

            // Get version number in x.x.x.x format
            // This information is available from the executing assembly
            //
            // PROBLEM: The following code assumes all assemblies have the same version,
            // culture, publickeytoken...This will break the scenarios where only one of
            // the assemblies is patched. ie., all monad assemblies should have the
            // same version number.
            AssemblyName assemblyName = typeof(PSSnapInReader).Assembly.GetName();
            assemblyVersion = assemblyName.Version;
            byte[] publicTokens = assemblyName.GetPublicKeyToken();
            if (publicTokens.Length == 0)
            {
                throw PSTraceSource.NewArgumentException("PublicKeyToken", MshSnapinInfo.PublicKeyTokenAccessFailed);
            }

            publicKeyToken = ConvertByteArrayToString(publicTokens);

            // save some cpu cycles by hardcoding the culture to neutral
            // assembly should never be targeted to a particular culture
            culture = "neutral";
        }

        /// <summary>
        /// PublicKeyToken is in the form of byte[]. Use this function to convert to a string.
        /// </summary>
        /// <param name="tokens">Array of byte's.</param>
        /// <returns></returns>
        internal static string ConvertByteArrayToString(byte[] tokens)
        {
            Dbg.Assert(tokens != null, "Input tokens should never be null");
            StringBuilder tokenBuilder = new StringBuilder(tokens.Length * 2);
            foreach (byte b in tokens)
            {
                tokenBuilder.Append(b.ToString("x2", CultureInfo.InvariantCulture));
            }

            return tokenBuilder.ToString();
        }

        /// <summary>
        /// Reads core snapin for monad engine.
        /// </summary>
        /// <returns>
        /// A PSSnapInInfo object
        /// </returns>
        internal static PSSnapInInfo ReadCoreEngineSnapIn()
        {
            ReadRegistryInfo(
                out Version assemblyVersion,
                out string publicKeyToken,
                out string culture,
                out string applicationBase,
                out Version psVersion);

            // System.Management.Automation formats & types files
            Collection<string> types = new Collection<string>(new string[] { "types.ps1xml", "typesv3.ps1xml" });
            Collection<string> formats = new Collection<string>(new string[]
                        {"Certificate.format.ps1xml", "DotNetTypes.format.ps1xml", "FileSystem.format.ps1xml",
                         "Help.format.ps1xml", "HelpV3.format.ps1xml", "PowerShellCore.format.ps1xml", "PowerShellTrace.format.ps1xml",
                         "Registry.format.ps1xml"});

            string strongName = string.Format(
                CultureInfo.InvariantCulture,
                "{0}, Version={1}, Culture={2}, PublicKeyToken={3}",
                s_coreSnapin.AssemblyName,
                assemblyVersion,
                culture,
                publicKeyToken);

            string moduleName = Path.Combine(applicationBase, s_coreSnapin.AssemblyName + ".dll");

            PSSnapInInfo coreMshSnapin = new PSSnapInInfo(
                s_coreSnapin.PSSnapInName,
                isDefault: true,
                applicationBase,
                strongName,
                moduleName,
                psVersion,
                assemblyVersion,
                types,
                formats,
                description: null,
                s_coreSnapin.Description,
                s_coreSnapin.DescriptionIndirect,
                vendor: null,
                vendorFallback: null,
                s_coreSnapin.VendorIndirect);
#if !UNIX
            // NOTE: On Unix, logging has to be deferred until after command-line parsing
            // complete. On Windows, deferring the call is not needed
            // and this is in the startup code path.
            SetSnapInLoggingInformation(coreMshSnapin);
#endif

            return coreMshSnapin;
        }

        /// <summary>
        /// Reads all registered mshsnapins for currently executing monad engine.
        /// </summary>
        /// <returns>
        /// A collection of PSSnapInInfo objects
        /// </returns>
        internal static Collection<PSSnapInInfo> ReadEnginePSSnapIns()
        {
            ReadRegistryInfo(
                out Version assemblyVersion,
                out string publicKeyToken,
                out string culture,
                out string applicationBase,
                out Version psVersion);

            // System.Management.Automation formats & types files
            Collection<string> smaFormats = new Collection<string>(new string[]
                        {"Certificate.format.ps1xml", "DotNetTypes.format.ps1xml", "FileSystem.format.ps1xml",
                         "Help.format.ps1xml", "HelpV3.format.ps1xml", "PowerShellCore.format.ps1xml", "PowerShellTrace.format.ps1xml",
                         "Registry.format.ps1xml"});
            Collection<string> smaTypes = new Collection<string>(new string[] { "types.ps1xml", "typesv3.ps1xml" });

            // create default mshsnapininfo objects..
            Collection<PSSnapInInfo> engineMshSnapins = new Collection<PSSnapInInfo>();
            string assemblyVersionString = assemblyVersion.ToString();

            for (int item = 0; item < DefaultMshSnapins.Count; item++)
            {
                DefaultPSSnapInInformation defaultMshSnapinInfo = DefaultMshSnapins[item];

                string strongName = string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}, Version={1}, Culture={2}, PublicKeyToken={3}",
                    defaultMshSnapinInfo.AssemblyName,
                    assemblyVersionString,
                    culture,
                    publicKeyToken);

                Collection<string> formats = null;
                Collection<string> types = null;

                if (defaultMshSnapinInfo.AssemblyName.Equals("System.Management.Automation", StringComparison.OrdinalIgnoreCase))
                {
                    formats = smaFormats;
                    types = smaTypes;
                }
                else if (defaultMshSnapinInfo.AssemblyName.Equals("Microsoft.PowerShell.Commands.Diagnostics", StringComparison.OrdinalIgnoreCase))
                {
                    types = new Collection<string>(new string[] { "GetEvent.types.ps1xml" });
                    formats = new Collection<string>(new string[] { "Event.format.ps1xml", "Diagnostics.format.ps1xml" });
                }
                else if (defaultMshSnapinInfo.AssemblyName.Equals("Microsoft.WSMan.Management", StringComparison.OrdinalIgnoreCase))
                {
                    formats = new Collection<string>(new string[] { "WSMan.format.ps1xml" });
                }

                string moduleName = Path.Combine(applicationBase, defaultMshSnapinInfo.AssemblyName + ".dll");

                PSSnapInInfo defaultMshSnapin = new PSSnapInInfo(
                    defaultMshSnapinInfo.PSSnapInName,
                    isDefault: true,
                    applicationBase,
                    strongName,
                    moduleName,
                    psVersion,
                    assemblyVersion,
                    types,
                    formats,
                    description: null,
                    defaultMshSnapinInfo.Description,
                    defaultMshSnapinInfo.DescriptionIndirect,
                    vendor: null,
                    vendorFallback: null,
                    defaultMshSnapinInfo.VendorIndirect);

                SetSnapInLoggingInformation(defaultMshSnapin);
                engineMshSnapins.Add(defaultMshSnapin);
            }

            return engineMshSnapins;
        }

        /// <summary>
        /// Enable Snapin logging based on group policy.
        /// </summary>
        private static void SetSnapInLoggingInformation(PSSnapInInfo psSnapInInfo)
        {
            IEnumerable<string> names;
            ModuleCmdletBase.ModuleLoggingGroupPolicyStatus status = ModuleCmdletBase.GetModuleLoggingInformation(out names);
            if (status != ModuleCmdletBase.ModuleLoggingGroupPolicyStatus.Undefined)
            {
                SetSnapInLoggingInformation(psSnapInInfo, status, names);
            }
        }

        /// <summary>
        /// Enable Snapin logging based on group policy.
        /// </summary>
        private static void SetSnapInLoggingInformation(PSSnapInInfo psSnapInInfo, ModuleCmdletBase.ModuleLoggingGroupPolicyStatus status, IEnumerable<string> moduleOrSnapinNames)
        {
            if (((status & ModuleCmdletBase.ModuleLoggingGroupPolicyStatus.Enabled) != 0) && moduleOrSnapinNames != null)
            {
                foreach (string currentGPModuleOrSnapinName in moduleOrSnapinNames)
                {
                    if (string.Equals(psSnapInInfo.Name, currentGPModuleOrSnapinName, StringComparison.OrdinalIgnoreCase))
                    {
                        psSnapInInfo.LogPipelineExecutionDetails = true;
                    }
                    else if (WildcardPattern.ContainsWildcardCharacters(currentGPModuleOrSnapinName))
                    {
                        WildcardPattern wildcard = WildcardPattern.Get(currentGPModuleOrSnapinName, WildcardOptions.IgnoreCase);
                        if (wildcard.IsMatch(psSnapInInfo.Name))
                        {
                            psSnapInInfo.LogPipelineExecutionDetails = true;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Get the key to monad root.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="SecurityException">
        /// Caller doesn't have access to monad registration information.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// Monad registration information is not available.
        /// </exception>
        internal static RegistryKey GetMonadRootKey()
        {
            RegistryKey rootKey = Registry.LocalMachine.OpenSubKey(RegistryStrings.MonadRootKeyPath);
            if (rootKey == null)
            {
                // This should never occur because this code is running
                // because monad is installed. { well this can occur if someone
                // deletes the registry key after starting monad
                Dbg.Assert(false, "Root Key of Monad installation is not present");
                throw PSTraceSource.NewArgumentException("monad", MshSnapinInfo.MonadRootRegistryAccessFailed);
            }

            return rootKey;
        }

        /// <summary>
        /// Get the registry key to PSEngine.
        /// </summary>
        /// <returns>RegistryKey.</returns>
        /// <param name="psVersion">Major version in string format.</param>
        /// <exception cref="ArgumentException">
        /// Monad registration information is not available.
        /// </exception>
        internal static RegistryKey GetPSEngineKey(string psVersion)
        {
            RegistryKey rootKey = GetMonadRootKey();
            // root key wont be null
            Dbg.Assert(rootKey != null, "Root Key of Monad installation is not present");

            RegistryKey versionRootKey = GetVersionRootKey(rootKey, psVersion);
            // version root key wont be null
            Dbg.Assert(versionRootKey != null, "Version Rootkey of Monad installation is not present");

            RegistryKey psEngineParentKey = rootKey.OpenSubKey(psVersion);
            if (psEngineParentKey == null)
            {
                throw PSTraceSource.NewArgumentException("monad", MshSnapinInfo.MonadEngineRegistryAccessFailed);
            }

            RegistryKey psEngineKey = psEngineParentKey.OpenSubKey(RegistryStrings.MonadEngineKey);
            if (psEngineKey == null)
            {
                throw PSTraceSource.NewArgumentException("monad", MshSnapinInfo.MonadEngineRegistryAccessFailed);
            }

            return psEngineKey;
        }

        /// <summary>
        /// Gets the version root key for specified monad version.
        /// </summary>
        /// <param name="rootKey"></param>
        /// <param name="psVersion"></param>
        /// <returns></returns>
        /// <exception cref="SecurityException">
        /// Caller doesn't have permission to read the version key
        /// </exception>
        /// <exception cref="ArgumentException">
        /// specified psVersion key is not present
        /// </exception>
        internal static
        RegistryKey
        GetVersionRootKey(RegistryKey rootKey, string psVersion)
        {
            Dbg.Assert(!string.IsNullOrEmpty(psVersion), "caller should validate the parameter");
            Dbg.Assert(rootKey != null, "caller should validate the parameter");

            string versionKey = PSVersionInfo.GetRegistryVersionKeyForSnapinDiscovery(psVersion);
            RegistryKey versionRoot = rootKey.OpenSubKey(versionKey);
            if (versionRoot == null)
            {
                throw PSTraceSource.NewArgumentException(nameof(psVersion), MshSnapinInfo.SpecifiedVersionNotFound, versionKey);
            }

            return versionRoot;
        }

        /// <summary>
        /// Gets the mshsnapin root key for specified monad version.
        /// </summary>
        /// <param name="versionRootKey"></param>
        /// <param name="psVersion"></param>
        /// <returns></returns>
        /// <exception cref="SecurityException">
        /// Caller doesn't have permission to read the mshsnapin key
        /// </exception>
        /// <exception cref="ArgumentException">
        /// mshsnapin key is not present
        /// </exception>
        private static
        RegistryKey
        GetMshSnapinRootKey(RegistryKey versionRootKey, string psVersion)
        {
            Dbg.Assert(versionRootKey != null, "caller should validate the parameter");

            RegistryKey mshsnapinRoot = versionRootKey.OpenSubKey(RegistryStrings.MshSnapinKey);
            if (mshsnapinRoot == null)
            {
                throw PSTraceSource.NewArgumentException(nameof(psVersion), MshSnapinInfo.NoMshSnapinPresentForVersion, psVersion);
            }

            return mshsnapinRoot;
        }

        /// <summary>
        /// Gets the mshsnapin key for specified monad version and mshsnapin name.
        /// </summary>
        /// <param name="mshSnapInName"></param>
        /// <param name="psVersion"></param>
        /// <returns></returns>
        /// <exception cref="SecurityException">
        /// Caller doesn't have permission to read the mshsnapin key
        /// </exception>
        /// <exception cref="ArgumentException">
        /// mshsnapin key is not present
        /// </exception>
        internal static
        RegistryKey
        GetMshSnapinKey(string mshSnapInName, string psVersion)
        {
            RegistryKey monadRootKey = GetMonadRootKey();
            RegistryKey versionRootKey = GetVersionRootKey(monadRootKey, psVersion);
            RegistryKey mshsnapinRoot = versionRootKey.OpenSubKey(RegistryStrings.MshSnapinKey);
            if (mshsnapinRoot == null)
            {
                throw PSTraceSource.NewArgumentException(nameof(psVersion), MshSnapinInfo.NoMshSnapinPresentForVersion, psVersion);
            }

            RegistryKey mshsnapinKey = mshsnapinRoot.OpenSubKey(mshSnapInName);
            return mshsnapinKey;
        }

        #region Default MshSnapins related structure

        /// <summary>
        /// This structure is meant to hold mshsnapin information for default mshsnapins.
        /// This is private only.
        /// </summary>
        private struct DefaultPSSnapInInformation
        {
            // since this is a private structure..making it as simple as possible
            public string PSSnapInName;
            public string AssemblyName;
            public string Description;
            public string DescriptionIndirect;
            public string VendorIndirect;

            public DefaultPSSnapInInformation(string sName,
                string sAssemblyName,
                string sDescription,
                string sDescriptionIndirect,
                string sVendorIndirect)
            {
                PSSnapInName = sName;
                AssemblyName = sAssemblyName;
                Description = sDescription;
                DescriptionIndirect = sDescriptionIndirect;
                VendorIndirect = sVendorIndirect;
            }
        }

        private static DefaultPSSnapInInformation s_coreSnapin =
            new DefaultPSSnapInInformation("Microsoft.PowerShell.Core", "System.Management.Automation", null,
                                           "CoreMshSnapInResources,Description", "CoreMshSnapInResources,Vendor");

        /// <summary>
        /// </summary>
        private static IList<DefaultPSSnapInInformation> DefaultMshSnapins
        {
            get
            {
                if (s_defaultMshSnapins == null)
                {
                    lock (s_syncObject)
                    {
#pragma warning disable IDE0074 // Disabling the rule because it can't be applied on non Unix
                        if (s_defaultMshSnapins == null)
#pragma warning restore IDE0074
                        {
                            s_defaultMshSnapins = new List<DefaultPSSnapInInformation>()
                            {
#if !UNIX
                                new DefaultPSSnapInInformation("Microsoft.PowerShell.Diagnostics", "Microsoft.PowerShell.Commands.Diagnostics", null,
                                    "GetEventResources,Description", "GetEventResources,Vendor"),
#endif
                                new DefaultPSSnapInInformation("Microsoft.PowerShell.Host", "Microsoft.PowerShell.ConsoleHost", null,
                                    "HostMshSnapInResources,Description", "HostMshSnapInResources,Vendor"),

                                s_coreSnapin,

                                new DefaultPSSnapInInformation("Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Commands.Utility", null,
                                    "UtilityMshSnapInResources,Description", "UtilityMshSnapInResources,Vendor"),

                                new DefaultPSSnapInInformation("Microsoft.PowerShell.Management", "Microsoft.PowerShell.Commands.Management", null,
                                    "ManagementMshSnapInResources,Description", "ManagementMshSnapInResources,Vendor"),

                                new DefaultPSSnapInInformation("Microsoft.PowerShell.Security", "Microsoft.PowerShell.Security", null,
                                    "SecurityMshSnapInResources,Description", "SecurityMshSnapInResources,Vendor")
                            };

#if !UNIX
                            if (!Utils.IsWinPEHost())
                            {
                                s_defaultMshSnapins.Add(new DefaultPSSnapInInformation("Microsoft.WSMan.Management", "Microsoft.WSMan.Management", null,
                                    "WsManResources,Description", "WsManResources,Vendor"));
                            }
#endif
                        }
                    }
                }

                return s_defaultMshSnapins;
            }
        }

        private static IList<DefaultPSSnapInInformation> s_defaultMshSnapins = null;
        private static readonly object s_syncObject = new object();

        #endregion

        private static readonly PSTraceSource s_mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false);
    }
}