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
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
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#if !UNIX

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Provider;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.XPath;

using Dbg = System.Management.Automation;
using DWORD = System.UInt32;
using Runspaces = System.Management.Automation.Runspaces;
using SMASecurity = System.Management.Automation.Security;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// Defines the Certificate Provider dynamic parameters.
    /// We only support one dynamic parameter for Win 7 and earlier:
    /// CodeSigningCert
    /// If provided, we only return certificates valid for signing code or
    /// scripts.
    /// </summary>
    internal sealed class CertificateProviderDynamicParameters
    {
        /// <summary>
        /// Gets or sets a switch that controls whether we only return
        /// code signing certs.
        /// </summary>
        [Parameter]
        public SwitchParameter CodeSigningCert
        {
            get { return _codeSigningCert; }

            set { _codeSigningCert = value; }
        }

        private SwitchParameter _codeSigningCert = new();

        /// <summary>
        /// Gets or sets a filter that controls whether we only return
        /// data encipherment certs.
        /// </summary>
        [Parameter]
        public SwitchParameter DocumentEncryptionCert
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a filter that controls whether we only return
        /// server authentication certs.
        /// </summary>
        [Parameter]
        public SwitchParameter SSLServerAuthentication
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a filter by DNSName.
        /// Expected content is a single DNS Name that may start and/or end
        /// with '*': "contoso.com" or "*toso.c*".
        /// All WildcardPattern class features supported.
        /// </summary>
        [Parameter]
        public string DnsName
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a filter by EKU.
        /// Expected content is one or more OID strings:
        /// "1.3.6.1.5.5.7.3.1", "*Server*", etc.
        /// For a cert to match, it must be valid for all listed OIDs.
        /// All WildcardPattern class features supported.
        /// </summary>
        [Parameter]
        public string[] Eku
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a filter by the number of valid days.
        /// Expected content is a non-negative integer.
        /// "0" matches all certs that have already expired.
        /// "1" matches all certs that are currently valid and will expire
        /// by next day (local time).
        /// </summary>
        [Parameter]
        [ValidateRange(ValidateRangeKind.NonNegative)]
        public int ExpiringInDays
        {
            get;
            set;
        } = -1;
    }

    /// <summary>
    /// Defines the type of DNS string
    /// The structure contains punycode name and unicode name.
    /// </summary>
    [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
    public readonly struct DnsNameRepresentation
    {
        /// <summary>
        /// Punycode version of DNS name.
        /// </summary>
        private readonly string _punycodeName;

        /// <summary>
        /// Unicode version of DNS name.
        /// </summary>
        private readonly string _unicodeName;

        /// <summary>
        /// Ambiguous constructor of a DnsNameRepresentation.
        /// </summary>
        public DnsNameRepresentation(string inputDnsName)
        {
            _punycodeName = inputDnsName;
            _unicodeName = inputDnsName;
        }

        /// <summary>
        /// Specific constructor of a DnsNameRepresentation.
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Punycode")]
        public DnsNameRepresentation(
            string inputPunycodeName,
            string inputUnicodeName)
        {
            _punycodeName = inputPunycodeName;
            _unicodeName = inputUnicodeName;
        }

        /// <summary>
        /// Value comparison.
        /// </summary>
        public bool Equals(DnsNameRepresentation dnsName)
        {
            bool match = false;

            if (_unicodeName != null && dnsName._unicodeName != null)
            {
                if (string.Equals(
                            _unicodeName,
                            dnsName._unicodeName,
                            StringComparison.OrdinalIgnoreCase))
                {
                    match = true;
                }
            }
            else if (_unicodeName == null && dnsName._unicodeName == null)
            {
                match = true;
            }

            return match;
        }

        /// <summary>
        /// Get property of Punycode.
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Punycode")]
        public string Punycode
        {
            get
            {
                return _punycodeName;
            }
        }

        /// <summary>
        /// Get property of Unicode.
        /// </summary>
        public string Unicode
        {
            get
            {
                return _unicodeName;
            }
        }

        /// <summary>
        /// Get display string.
        /// </summary>
        public override string ToString()
        {
            // Use case sensitive comparison here.
            // We don't ever expect to see the punycode and unicode strings
            // to differ only by upper/lower case.  If they do, that's really
            // a code bug, and the effect is to just display both strings.

            return string.Equals(_punycodeName, _unicodeName, StringComparison.Ordinal)
                ? _punycodeName
                : _unicodeName + " (" + _punycodeName + ")";
        }
    }

    /// <summary>
    /// Defines the Certificate Provider remove-item dynamic parameters.
    ///
    /// Currently, we only support one dynamic parameter: DeleteKey
    /// If provided, we will delete the private key when we remove a certificate.
    /// </summary>
    internal sealed class ProviderRemoveItemDynamicParameters
    {
        /// <summary>
        /// Switch that controls whether we should delete private key
        /// when remove a certificate.
        /// </summary>
        [Parameter]
        public SwitchParameter DeleteKey
        {
            get
            {
                {
                    return _deleteKey;
                }
            }

            set
            {
                {
                    _deleteKey = value;
                }
            }
        }

        private SwitchParameter _deleteKey = new();
    }

    /// <summary>
    /// Defines the safe handle class for native cert store handles,
    /// HCERTSTORE.
    /// </summary>
    internal sealed class CertificateStoreHandle : SafeHandle
    {
        public CertificateStoreHandle() : base(IntPtr.Zero, true)
        {
            return;
        }

        public override bool IsInvalid
        {
            get { return handle == IntPtr.Zero; }
        }

        protected override bool ReleaseHandle()
        {
            bool fResult = false;

            if (handle != IntPtr.Zero)
            {
                fResult = SMASecurity.NativeMethods.CertCloseStore(handle, 0);
                handle = IntPtr.Zero;
            }

            return fResult;
        }

        public IntPtr Handle
        {
            get { return handle; }

            set { handle = value; }
        }
    }

    /// <summary>
    /// Defines the Certificate Provider store handle class.
    /// </summary>
    internal sealed class X509NativeStore
    {
        // #region tracer

        /// <summary>
        /// Initializes a new instance of the X509NativeStore class.
        /// </summary>
        public X509NativeStore(X509StoreLocation StoreLocation, string StoreName)
        {
            _storeLocation = StoreLocation;
            _storeName = StoreName;
        }

        public void Open(bool includeArchivedCerts)
        {
            if (_storeHandle != null && _archivedCerts != includeArchivedCerts)
            {
                _storeHandle = null;        // release the old handle
            }

            if (_storeHandle == null)
            {
                _valid = false;
                _open = false;

                SMASecurity.NativeMethods.CertOpenStoreFlags StoreFlags =
                    SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_SHARE_STORE_FLAG |
                    SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_SHARE_CONTEXT_FLAG |
                    SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_OPEN_EXISTING_FLAG |
                    SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG;

                if (includeArchivedCerts)
                {
                    StoreFlags |= SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG;
                }

                switch (_storeLocation.Location)
                {
                    case StoreLocation.LocalMachine:
                        StoreFlags |= SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE;
                        break;

                    case StoreLocation.CurrentUser:
                        StoreFlags |= SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER;
                        break;

                    default:
                        // ThrowItemNotFound(storeLocation.ToString(), CertificateProviderItem.StoreLocation);
                        break;
                }

                IntPtr hCertStore = SMASecurity.NativeMethods.CertOpenStore(
                                SMASecurity.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM,
                                SMASecurity.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING,
                                IntPtr.Zero,  // hCryptProv
                                StoreFlags,
                                _storeName);
                if (hCertStore == IntPtr.Zero)
                {
                    throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                }

                _storeHandle = new CertificateStoreHandle();
                _storeHandle.Handle = hCertStore;

                // we only do CertControlStore for stores other than UserDS
                if (!string.Equals(
                                _storeName,
                                "UserDS",
                                StringComparison.OrdinalIgnoreCase))
                {
                    if (!SMASecurity.NativeMethods.CertControlStore(
                                _storeHandle.Handle,
                                0,
                                SMASecurity.NativeMethods.CertControlStoreType.CERT_STORE_CTRL_AUTO_RESYNC,
                                IntPtr.Zero))
                    {
                        _storeHandle = null;
                        throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                    }
                }

                _valid = true;
                _open = true;
                _archivedCerts = includeArchivedCerts;
            }
        }

        public IntPtr GetFirstCert()
        {
            return GetNextCert(IntPtr.Zero);
        }

        public IntPtr GetNextCert(IntPtr certContext)
        {
            if (!_open)
            {
                throw Marshal.GetExceptionForHR(
                                    SMASecurity.NativeMethods.CRYPT_E_NOT_FOUND);
            }

            if (Valid)
            {
                certContext = SMASecurity.NativeMethods.CertEnumCertificatesInStore(
                                                    _storeHandle.Handle,
                                                    certContext);
            }
            else
            {
                certContext = IntPtr.Zero;
            }

            return certContext;
        }

        public IntPtr GetCertByName(string Name)
        {
            IntPtr certContext = IntPtr.Zero;

            if (!_open)
            {
                throw Marshal.GetExceptionForHR(
                                    SMASecurity.NativeMethods.CRYPT_E_NOT_FOUND);
            }

            if (Valid)
            {
                if (DownLevelHelper.HashLookupSupported())
                {
                    certContext = SMASecurity.NativeMethods.CertFindCertificateInStore(
                            _storeHandle.Handle,
                            SMASecurity.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING,
                            0,                                // dwFindFlags
                            SMASecurity.NativeMethods.CertFindType.CERT_FIND_HASH_STR,
                            Name,
                            IntPtr.Zero);                     // pPrevCertContext
                }
                else
                {
                    //
                    // the pre-Win8 CAPI2 code does not provide an easy way
                    // to directly access a specific certificate.
                    // We have to iterate through all certs to find
                    // what we want.
                    //

                    while (true)
                    {
                        certContext = GetNextCert(certContext);
                        if (certContext == IntPtr.Zero)
                        {
                            break;
                        }

                        X509Certificate2 cert = new(certContext);
                        if (string.Equals(
                                    cert.Thumbprint,
                                    Name,
                                    StringComparison.OrdinalIgnoreCase))
                        {
                            break;
                        }
                    }
                }
            }

            return certContext;
        }

        public void FreeCert(IntPtr certContext)
        {
            SMASecurity.NativeMethods.CertFreeCertificateContext(certContext);
        }

        /// <summary>
        /// Native IntPtr store handle.
        /// </summary>
        public IntPtr StoreHandle
        {
            get
            {
                return _storeHandle.Handle;
            }
        }

        /// <summary>
        /// X509StoreLocation store location.
        /// </summary>
        public X509StoreLocation Location
        {
            get
            {
                return _storeLocation;
            }
        }

        /// <summary>
        /// String store name.
        /// </summary>
        public string StoreName
        {
            get
            {
                return _storeName;
            }
        }

        /// <summary>
        /// True if a real store is open.
        /// </summary>
        public bool Valid
        {
            get
            {
                return _valid;
            }
        }

        private bool _archivedCerts = false;
        private readonly X509StoreLocation _storeLocation = null;
        private readonly string _storeName = null;
        private CertificateStoreHandle _storeHandle = null;
        private bool _valid = false;
        private bool _open = false;
    }

    /// <summary>
    /// Defines the types of items
    /// supported by the certificate provider.
    /// </summary>
    internal enum CertificateProviderItem
    {
        /// <summary>
        /// An unknown item.
        /// </summary>
        Unknown,

        /// <summary>
        /// An X509 Certificate.
        /// </summary>
        Certificate,

        /// <summary>
        /// A certificate store location.
        /// For example, cert:\CurrentUser.
        /// </summary>
        Store,

        /// <summary>
        /// A certificate store.
        /// For example, cert:\CurrentUser\My.
        /// </summary>
        StoreLocation
    }

    /// <summary>
    /// Defines the implementation of a Certificate Store Provider.  This provider
    /// allows for stateless namespace navigation of the computer's certificate
    /// store.
    /// </summary>
    [CmdletProvider("Certificate", ProviderCapabilities.ShouldProcess)]
    [OutputType(typeof(string), typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.ResolvePath)]
    [OutputType(typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.PushLocation)]
    [OutputType(typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.PopLocation)]
    [OutputType(typeof(Microsoft.PowerShell.Commands.X509StoreLocation), typeof(X509Certificate2), ProviderCmdlet = ProviderCmdlet.GetItem)]
    [OutputType(typeof(X509Store), typeof(X509Certificate2), ProviderCmdlet = ProviderCmdlet.GetChildItem)]
    public sealed class CertificateProvider : NavigationCmdletProvider, ICmdletProviderSupportsHelp
    {
        #region tracer

        /// <summary>
        /// Tracer for certificate provider.
        /// </summary>
        [TraceSource("CertificateProvider",
                      "The core command provider for certificates")]
        private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("CertificateProvider",
                      "The core command provider for certificates");

        #endregion tracer

        /// <summary>
        /// Indicate if we already have attempted to load the PKI module.
        /// </summary>
        private bool _hasAttemptedToLoadPkiModule = false;

        /// <summary>
        /// Lock that guards access to the following static members
        /// -- storeLocations
        /// -- pathCache.
        /// </summary>
        private static readonly object s_staticLock = new();

        /// <summary>
        /// List of store locations. They do not change once initialized.
        ///
        /// Synchronized on staticLock.
        /// </summary>
        private static List<X509StoreLocation> s_storeLocations = null;

        /// <summary>
        /// Cache that stores paths and their associated objects.
        ///
        /// key is full path to store-location/store/certificate
        /// value is X509StoreLocation/X509NativeStore/X509Certificate2 object
        ///
        /// Synchronized on staticLock.
        /// </summary>
        private static Hashtable s_pathCache = null;

        /// <summary>
        /// We allow either / or \ to be the path separator.
        /// </summary>
        private static readonly char[] s_pathSeparators = new char[] { '/', '\\' };

        /// <summary>
        /// Regex pattern that defines a valid cert path.
        /// </summary>
        private const string certPathPattern = @"^\\((?<StoreLocation>CurrentUser|LocalMachine)(\\(?<StoreName>[a-zA-Z]+)(\\(?<Thumbprint>[0-9a-f]{40}))?)?)?$";

        /// <summary>
        /// Cache the store handle to avoid repeated CertOpenStore calls.
        /// </summary>
        private static X509NativeStore s_storeCache = null;

        /// <summary>
        /// On demand create the Regex to avoid a hit to startup perf.
        /// </summary>
        /// <remarks>
        /// Note, its OK that staticLock is being used here because only
        /// IsValidPath is calling this static property so we shouldn't
        /// have any deadlocks due to other locked static members calling
        /// this property.
        /// </remarks>
        private static Regex s_certPathRegex = null;

        private static Regex CertPathRegex
        {
            get
            {
                lock (s_staticLock)
                {
                    if (s_certPathRegex == null)
                    {
                        const RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled;
                        s_certPathRegex = new Regex(certPathPattern, options);
                    }
                }

                return s_certPathRegex;
            }
        }

        /// <summary>
        /// Initializes a new instance of the CertificateProvider class.
        /// This initializes the default certificate store locations.
        /// </summary>
        public CertificateProvider()
        {
            //
            // initialize storeLocations list and also update the cache
            //
            lock (s_staticLock)
            {
                if (s_storeLocations == null)
                {
                    s_pathCache = new Hashtable(StringComparer.OrdinalIgnoreCase);
                    s_storeLocations =
                        new List<X509StoreLocation>();

                    //
                    // create and cache CurrentUser store-location
                    //
                    X509StoreLocation user = new(StoreLocation.CurrentUser);
                    s_storeLocations.Add(user);
                    AddItemToCache(nameof(StoreLocation.CurrentUser),
                                  user);

                    //
                    // create and cache LocalMachine store-location
                    //
                    X509StoreLocation machine = new(StoreLocation.LocalMachine);
                    s_storeLocations.Add(machine);
                    AddItemToCache(nameof(StoreLocation.LocalMachine),
                                   machine);

                    AddItemToCache(string.Empty, s_storeLocations);
                }
            }
        }

        /// <summary>
        /// Removes an item at the specified path.
        /// </summary>
        /// <param name="path">
        /// The path of the item to remove.
        /// </param>
        /// <param name="recurse">
        /// Recursively remove.
        /// </param>
        /// <returns>
        /// Nothing.
        /// </returns>
        /// <exception cref="System.ArgumentException">
        ///     path is null or empty.
        ///     destination is null or empty.
        /// </exception>
        protected override void RemoveItem(
                                string path,
                                bool recurse)
        {
            path = NormalizePath(path);
            bool isContainer = false;
            bool fDeleteKey = false;

            object outObj = GetItemAtPath(path, false, out isContainer);
            string[] pathElements = GetPathElements(path);

            bool fUserContext = string.Equals(pathElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase);

            // isContainer = true means not a valid certificate

            // if source store is user root store and UI is not allowed
            // we raise invalid operation
            if (DetectUIHelper.GetOwnerWindow(Host) == IntPtr.Zero && fUserContext &&
                 string.Equals(pathElements[1], "ROOT", StringComparison.OrdinalIgnoreCase))
            {
                string message = CertificateProviderStrings.UINotAllowed;
                const string errorId = "UINotAllowed";
                ThrowInvalidOperation(errorId, message);
            }

            if (DynamicParameters != null && DynamicParameters is ProviderRemoveItemDynamicParameters dp)
            {
                if (dp.DeleteKey)
                {
                    fDeleteKey = true;
                }
            }

            if (isContainer)
            {
                if (pathElements.Length == 2) // is a store
                {
                    // not support user context
                    if (fUserContext)
                    {
                        string message = CertificateProviderStrings.CannotDeleteUserStore;
                        const string errorId = "CannotDeleteUserStore";
                        ThrowInvalidOperation(errorId, message);
                    }

                    RemoveCertStore(pathElements[1], fDeleteKey, path);
                    return;
                }
                else // other container than a store
                {
                    string message = CertificateProviderStrings.CannotRemoveContainer;
                    const string errorId = "CannotRemoveContainer";
                    ThrowInvalidOperation(errorId, message);
                }
            }
            else // certificate
            {
                // do remove
                X509Certificate2 certificate = outObj as X509Certificate2;
                RemoveCertItem(certificate, fDeleteKey, !fUserContext, path);
                return;
            }
        }

        /// <summary>
        /// Gets the dynamic parameters for remove-item on the Certificate
        /// Provider.  We currently only support one dynamic parameter,
        /// "DeleteKey," that delete private key when we delete a certificate.
        /// </summary>
        /// <param name="path">
        /// If the path was specified on the command line, this is the path
        /// to the item for which to get the dynamic parameters.
        /// </param>
        /// <param name="recurse">
        /// Ignored.
        /// </param>
        /// <returns>
        /// An object that has properties and fields decorated with
        /// parsing attributes similar to a cmdlet class.
        /// </returns>
        protected override object RemoveItemDynamicParameters(string path, bool recurse)
        {
            return new ProviderRemoveItemDynamicParameters();
        }

        /// <summary>
        /// Moves an item at the specified path to the given destination.
        /// </summary>
        /// <param name="path">
        /// The path of the item to move.
        /// </param>
        /// <param name="destination">
        /// The path of the destination.
        /// </param>
        /// <returns>
        /// Nothing.  Moved items are written to the context's pipeline.
        /// </returns>
        /// <exception cref="System.ArgumentException">
        ///     path is null or empty.
        ///     destination is null or empty.
        /// </exception>
        protected override void MoveItem(
                                string path,
                                string destination)
        {
            // normalize path
            path = NormalizePath(path);
            destination = NormalizePath(destination);

            // get elements from the path
            string[] pathElements = GetPathElements(path);
            string[] destElements = GetPathElements(destination);

            bool isContainer = false;
            object cert = GetItemAtPath(path, false, out isContainer);

            //
            // isContainer = true; means an invalid path
            //
            if (isContainer)
            {
                string message = CertificateProviderStrings.CannotMoveContainer;
                const string errorId = "CannotMoveContainer";
                ThrowInvalidOperation(errorId, message);
            }

            if (destElements.Length != 2) // not a store
            {
                // if the destination leads to the same thumbprint
                if (destElements.Length == 3 &&
                   (string.Equals(pathElements[2], destElements[2], StringComparison.OrdinalIgnoreCase)))
                {
                    // in this case we think of destination path as valid
                    // and strip the thumbprint part
                    destination = Path.GetDirectoryName(destination);
                }
                else
                {
                    string message = CertificateProviderStrings.InvalidDestStore;
                    const string errorId = "InvalidDestStore";
                    ThrowInvalidOperation(errorId, message);
                }
            }

            // the second element is store location
            // we do not allow cross context move
            // we do not allow the destination store is the same as source

            if (!string.Equals(pathElements[0], destElements[0], StringComparison.OrdinalIgnoreCase))
            {
                string message = CertificateProviderStrings.CannotMoveCrossContext;
                const string errorId = "CannotMoveCrossContext";
                ThrowInvalidOperation(errorId, message);
            }

            if (string.Equals(pathElements[1], destElements[1], StringComparison.OrdinalIgnoreCase))
            {
                string message = CertificateProviderStrings.CannotMoveToSameStore;
                const string errorId = "CannotMoveToSameStore";
                ThrowInvalidOperation(errorId, message);
            }

            // if source or destination store is user root store and UI is not allowed
            // we raise invalid operation
            if (DetectUIHelper.GetOwnerWindow(Host) == IntPtr.Zero)
            {
                if ((string.Equals(pathElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase) &&
                     string.Equals(pathElements[1], "ROOT", StringComparison.OrdinalIgnoreCase)) ||
                     (string.Equals(destElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase) &&
                     string.Equals(destElements[1], "ROOT", StringComparison.OrdinalIgnoreCase)))
                {
                    string message = CertificateProviderStrings.UINotAllowed;
                    const string errorId = "UINotAllowed";
                    ThrowInvalidOperation(errorId, message);
                }
            }

            if (cert != null) // we get cert
            {
                // get destination store
                bool isDestContainer = false;
                object store = GetItemAtPath(destination, false, out isDestContainer);

                X509Certificate2 certificate = cert as X509Certificate2;

                if (store is X509NativeStore certstore)
                {
                    certstore.Open(true);

                    string action = CertificateProviderStrings.Action_Move;
                    string resource = string.Format(
                                          CultureInfo.CurrentCulture,
                                          CertificateProviderStrings.MoveItemTemplate,
                                          path,
                                          destination);
                    if (ShouldProcess(resource, action))
                    {
                        DoMove(destination, certificate, certstore, path);
                    }
                }
            }
            else
            {
                ThrowItemNotFound(path, CertificateProviderItem.Certificate);
            }
        }

        /// <summary>
        /// Creates a certificate store with the given path.
        /// </summary>
        /// <remarks>
        /// New-Item doesn't go through the method "ItemExists". But for the
        /// CertificateProvider, New-Item can create an X509Store and return
        /// it, and the user can access the certificates within the store via its
        /// property "Certificates". We want the extra new properties of the
        /// X509Certificate2 objects to be shown to the user, so we also need
        /// to import the PKI module in this method, if we haven't tried it yet.
        /// </remarks>
        /// <param name="path">
        /// The path of the certificate store to create.
        /// </param>
        /// <param name="type">
        /// Ignored.
        /// Only support store.
        /// </param>
        /// <param name="value">
        /// Ignored
        /// </param>
        /// <returns>
        /// Nothing.  The new certificate store object is
        /// written to the context's pipeline.
        /// </returns>
        /// <exception cref="System.ArgumentException">
        ///     path is null or empty.
        /// </exception>
        protected override void NewItem(
                string path,
                string type,
                object value)
        {
            if (!_hasAttemptedToLoadPkiModule)
            {
                // Attempt to load the PKI module if we haven't tried yet
                AttemptToImportPkiModule();
            }

            path = NormalizePath(path);

            // get the elements from the path
            string[] pathElements = GetPathElements(path);

            // only support creating store
            if (pathElements.Length != 2)
            {
                string message = CertificateProviderStrings.CannotCreateItem;
                const string errorId = "CannotCreateItem";
                ThrowInvalidOperation(errorId, message);
            }

            bool fUserContext = string.Equals(pathElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase);

            // not support user context
            if (fUserContext)
            {
                string message = CertificateProviderStrings.CannotCreateUserStore;
                const string errorId = "CannotCreateUserStore";
                ThrowInvalidOperation(errorId, message);
            }

            const SMASecurity.NativeMethods.CertOpenStoreFlags StoreFlags =
                    SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_CREATE_NEW_FLAG |
                    SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG |
                    SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE;

            // Create new store
            IntPtr hCertStore = SMASecurity.NativeMethods.CertOpenStore(
                                SMASecurity.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM,
                                SMASecurity.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING,
                                IntPtr.Zero,  // hCryptProv
                                StoreFlags,
                                pathElements[1]);
            if (hCertStore == IntPtr.Zero)
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }
            else // free native store handle
            {
                bool fResult = false;
                fResult = SMASecurity.NativeMethods.CertCloseStore(hCertStore, 0);
            }

            X509Store outStore = new(pathElements[1], StoreLocation.LocalMachine);
            WriteItemObject(outStore, path, true);
        }

        #region DriveCmdletProvider overrides

        /// <summary>
        /// Initializes the cert: drive.
        /// </summary>
        /// <returns>
        /// A collection that contains the PSDriveInfo object
        /// that represents the cert: drive.
        /// </returns>
        protected override Collection<PSDriveInfo> InitializeDefaultDrives()
        {
            string providerDescription = CertificateProviderStrings.CertProvidername;

            PSDriveInfo drive = new(
                name: "Cert",
                provider: ProviderInfo,
                root: @"\",
                providerDescription,
                credential: null);

            Collection<PSDriveInfo> drives = new();
            drives.Add(drive);

            return drives;
        }

        /// <summary>
        /// Determines if the item at the given path is a store-location
        /// or store with items in it.
        /// </summary>
        /// <param name="path">
        /// The full path to the item.
        /// </param>
        /// <returns>
        /// True if the path refers to a store location, or store that contains
        /// certificates.  False otherwise.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// Path is null
        /// </exception>
        /// <exception cref="System.Security.Cryptography.CryptographicException">
        /// This exception can be thrown if any cryptographic error occurs.
        /// It is not possible to know exactly what went wrong.
        /// This is because of the way CryptographicException is designed.
        /// Some example reasons include:
        ///  -- certificate is invalid
        ///  -- certificate has no private key
        ///  -- certificate password mismatch
        /// </exception>
        protected override bool HasChildItems(string path)
        {
            bool result = false;

            Utils.CheckArgForNull(path, "path");

            path = NormalizePath(path);

            if (path.Length == 0)
            {
                return true;
            }

            bool isContainer = false;

            object item = GetItemAtPath(path, false, out isContainer);

            if ((item != null) && isContainer)
            {
                if (item is X509StoreLocation storeLocation)
                {
                    result = storeLocation.StoreNames.Count > 0;
                }
                else if (item is X509NativeStore store)
                {
                    store.Open(IncludeArchivedCerts());
                    IntPtr certContext = store.GetFirstCert();
                    if (certContext != IntPtr.Zero)
                    {
                        store.FreeCert(certContext);
                        result = true;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// Determines if the specified path is syntactically and semantically valid.
        /// An example path looks like this:
        ///     cert:\CurrentUser\My\5F98EBBFE735CDDAE00E33E0FD69050EF9220254.
        /// </summary>
        /// <param name="path">
        /// The path of the item to check.
        /// </param>
        /// <returns>
        /// True if the path is valid, false otherwise.
        /// </returns>
        protected override bool IsValidPath(string path)
        {
            path = NormalizePath(path);
            path = EnsureDriveIsRooted(path);

            bool isCertPath = CertPathRegex.Match(path).Success;

            return isCertPath;
        }

        /// <summary>
        /// Determines if the store location, store, or certificate exists
        /// at the specified path.
        /// </summary>
        /// <remarks>
        /// The method ItemExists will be hit by all built-in cmdlets that interact
        /// with the CertificateProvider except for the New-Item. They are:
        ///     Get-ChildItem
        ///     Set-Location
        ///     Push-Location
        ///     Pop-Location
        ///     Move-Item
        ///     Invoke-Item
        ///     Get-Item
        ///     Remove-Item
        /// So we import the PKI module in this method if we haven't tried yet.
        /// </remarks>
        /// <param name="path">
        /// The path of the item to check.
        /// </param>
        /// <returns>
        /// True if a the store location, store, or certificate exists
        /// at the specified path.  False otherwise.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// Path is null
        /// </exception>
        /// <exception cref="System.Security.Cryptography.CryptographicException">
        /// This exception can be thrown if any cryptographic error occurs.
        /// It is not possible to know exactly what went wrong.
        /// This is because of the way CryptographicException is designed.
        /// Possible reasons:
        ///  -- certificate is invalid
        ///  -- certificate has no private key
        ///  -- certificate password mismatch
        ///  -- etc
        /// </exception>
        protected override bool ItemExists(string path)
        {
            if (!_hasAttemptedToLoadPkiModule)
            {
                // Attempt to load the PKI module if we haven't tried yet
                AttemptToImportPkiModule();
            }

            Utils.CheckArgForNull(path, "path");
            bool result = false;
            bool isContainer = false;
            object item = null;

            path = NormalizePath(path);

            if (path.Length == 0)
            {
                result = true;
            }
            else
            {
                //
                // We fetch the item to see if it exists. This is
                // because the managed cert infrastructure does not
                // provide a way to test for existence.
                //
                try
                {
                    item = GetItemAtPath(path, true, out isContainer);
                }
                catch (ProviderInvocationException e)
                {
                    //
                    // if the item is not found, we get ProviderInvocationException
                    // with inner exception set to CertificateProviderItemNotFoundException
                    // If the inner exception is not of that type
                    // then we need to rethrow
                    //
                    if (e.InnerException is not CertificateProviderItemNotFoundException)
                    {
                        throw;
                    }
                }

                result = (bool)item;
            }

            s_tracer.WriteLine("result = {0}", result);
            return result;
        }

        /// <summary>
        /// Gets the store location, store, or certificate
        /// at the specified path.
        /// </summary>
        /// <param name="path">
        /// The path of the item to retrieve.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Path is null
        /// </exception>
        /// <exception cref="System.Security.Cryptography.CryptographicException">
        /// This exception can be thrown if any cryptographic error occurs.
        /// It is not possible to know exactly what went wrong.
        /// This is because of the way CryptographicException is designed.
        /// Possible reasons:
        ///  -- certificate is invalid
        ///  -- certificate has no private key
        ///  -- certificate password mismatch
        ///  -- etc
        /// </exception>
        protected override void GetItem(string path)
        {
            bool isContainer = false;

            path = NormalizePath(path);
            object item = GetItemAtPath(path, false, out isContainer);
            CertificateFilterInfo filter = GetFilter();

            if (item != null)
            {
                if (!isContainer) // certificate
                {
                    // If the filter is null, output the certificate we got.
                    if (filter == null)
                    {
                        WriteItemObject(item, path, isContainer);
                    }
                    else
                    {
                        // The filter is non null. If the certificate
                        // satisfies the filter, output it. Otherwise, don't.
                        X509Certificate2 cert = item as X509Certificate2;
                        Dbg.Diagnostics.Assert(cert != null, "item should be a certificate");

                        if (MatchesFilter(cert, filter))
                        {
                            WriteItemObject(item, path, isContainer);
                        }
                    }
                }
                else  // container
                {
                    // The item is a container. If the filter is non null, we don't output it.
                    if (filter != null)
                    {
                        return;
                    }

                    if (item is X509StoreLocation storeLocation)  // store location
                    {
                        WriteItemObject(item, path, isContainer);
                    }
                    else if (item is X509NativeStore store) // store
                    {
                        // create X509Store
                        X509Store outStore = new(store.StoreName, store.Location.Location);
                        WriteItemObject(outStore, path, isContainer);
                    }
                }
            }
        }

        /// <summary>
        /// Gets the parent of the given path.
        /// </summary>
        /// <param name="path">
        /// The path of which to get the parent.
        /// </param>
        /// <param name="root">
        /// The root of the drive.
        /// </param>
        /// <returns>
        /// The parent of the given path.
        /// </returns>
        protected override string GetParentPath(string path, string root)
        {
            string parentPath = base.GetParentPath(path, root);

            return parentPath;
        }

        /// <summary>
        /// Gets the name of the leaf element of the specified path.
        /// </summary>
        /// <param name="path">
        /// The fully qualified path to the item.
        /// </param>
        /// <returns>
        /// The leaf element of the specified path.
        /// </returns>
        protected override string GetChildName(string path)
        {
            // Path for root is empty string
            if (path != null && path.Length == 0)
            {
                return path;
            }
            else
            {
                return MyGetChildName(path);
            }
        }

        /// <summary>
        /// We want to import the PKI module explicitly because a type for X509Certificate
        /// is defined in the PKI module that add new properties to the X509Certificate2
        /// objects. We want to show those new properties to the user without requiring
        /// someone to force the loading of this module.
        /// </summary>
        private void AttemptToImportPkiModule()
        {
            const string moduleName = "pki";

            if (Runspaces.Runspace.DefaultRunspace == null)
            {
                //
                // Requires default runspace. Only import the module.
                // when a default runspace is available.
                //

                return;
            }

            CommandInfo commandInfo =
                new CmdletInfo(
                    "Import-Module",
                     typeof(Microsoft.PowerShell.Commands.ImportModuleCommand));
            Runspaces.Command importModuleCommand = new(commandInfo);

            s_tracer.WriteLine("Attempting to load module: {0}", moduleName);

            try
            {
                System.Management.Automation.PowerShell ps = null;
                ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace)
                            .AddCommand(importModuleCommand)
                                .AddParameter("Name", moduleName)
                                .AddParameter("Scope", StringLiterals.Global)
                                .AddParameter("ErrorAction", ActionPreference.Ignore)
                                .AddParameter("WarningAction", ActionPreference.Ignore)
                                .AddParameter("InformationAction", ActionPreference.Ignore)
                                .AddParameter("Verbose", false)
                                .AddParameter("Debug", false);
                ps.Invoke();
            }
            catch (Exception)
            {
            }

            _hasAttemptedToLoadPkiModule = true;
        }

        private static string MyGetChildName(string path)
        {
            // Verify the parameters

            if (string.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentException(nameof(path));
            }

            // Normalize the path
            path = path.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator);

            // Trim trailing back slashes
            path = path.TrimEnd(StringLiterals.DefaultPathSeparator);
            string result = null;

            int separatorIndex = path.LastIndexOf(StringLiterals.DefaultPathSeparator);

            // Since there was no path separator return the entire path
            if (separatorIndex == -1)
            {
                result = path;
            }
            else
            {
                result = path.Substring(separatorIndex + 1);
            }

            return result;
        }
        /// <summary>
        /// Invokes the certificate management UI (certmgr.msc)
        /// for any path.
        /// </summary>
        /// <param name="path">
        /// Ignored.
        /// </param>
        protected override void InvokeDefaultAction(string path)
        {
            path = NormalizePath(path);
            string action = CertificateProviderStrings.Action_Invoke;
            const string certmgr = "certmgr.msc";
            string certPath = System.IO.Path.Combine(
                System.Environment.ExpandEnvironmentVariables("%windir%"), "system32");

            if (ShouldProcess(path, action))
            {
                System.Diagnostics.Process.Start(System.IO.Path.Combine(certPath, certmgr));
            }
        }

        private static string EnsureDriveIsRooted(string path)
        {
            string result = path;

            // Find the drive separator
            int index = path.IndexOf(':');

            if (index != -1)
            {
                // if the drive separator is the end of the path, add
                // the root path separator back
                if (index + 1 == path.Length)
                {
                    result = path + StringLiterals.DefaultPathSeparator;
                }
            }
            else if ((path.Length == 0) || (path[0] != StringLiterals.DefaultPathSeparator))
            {
                result = StringLiterals.DefaultPathSeparator + path;
            }

            s_tracer.WriteLine("result = {0}", result);
            return result;
        }

        private static ErrorRecord CreateErrorRecord(string path,
                                              CertificateProviderItem itemType)
        {
            Exception e = null;
            string message = null;

            //
            // first, find the resource-id so that we can display
            // correct message
            //
            switch (itemType)
            {
                case CertificateProviderItem.Certificate:
                    message = CertificateProviderStrings.CertificateNotFound;
                    break;

                case CertificateProviderItem.Store:
                    message = CertificateProviderStrings.CertificateStoreNotFound;
                    break;

                case CertificateProviderItem.StoreLocation:
                    message = CertificateProviderStrings.CertificateStoreLocationNotFound;
                    break;

                default:
                    message = CertificateProviderStrings.InvalidPath;
                    break;
            }

            message = string.Format(
                System.Globalization.CultureInfo.CurrentCulture,
                message, path);
            ErrorDetails ed = new(message);

            //
            // create appropriate exception type
            //
            switch (itemType)
            {
                case CertificateProviderItem.Certificate:
                    e = new CertificateNotFoundException(message);
                    break;

                case CertificateProviderItem.Store:
                    e = new CertificateStoreNotFoundException(message);
                    break;

                case CertificateProviderItem.StoreLocation:
                    e = new CertificateStoreLocationNotFoundException(message);
                    break;

                default:
                    e = new ArgumentException(message);
                    break;
            }

            ErrorRecord er = new(
                e,
                "CertProviderItemNotFound",
                ErrorCategory.ObjectNotFound,
                targetObject: null);

            er.ErrorDetails = ed;

            return er;
        }

        private void ThrowErrorRemoting(int stat)
        {
            if (this.Host.Name.Equals("ServerRemoteHost", StringComparison.OrdinalIgnoreCase))
            {
                Exception e = new System.ComponentModel.Win32Exception(stat);
                string error = e.Message;
                string message = CertificateProviderStrings.RemoteErrorMessage;
                error += message;

                Exception e2 = new(error);
                ThrowTerminatingError(
                        new ErrorRecord(
                            e2,
                            "RemotingFailure",
                            ErrorCategory.NotSpecified,
                            null));
            }
            else
            {
                throw new System.ComponentModel.Win32Exception(stat);
            }
        }

        private void ThrowInvalidOperation(string errorId, string message)
        {
            ErrorRecord errorRecord = new(
                new InvalidOperationException(message),
                errorId,
                ErrorCategory.InvalidOperation,
                targetObject: null);
            errorRecord.ErrorDetails = new ErrorDetails(message);
            ThrowTerminatingError(errorRecord);

            return;
        }

        private void ThrowItemNotFound(string path,
                                       CertificateProviderItem itemType)
        {
            ErrorRecord er = CreateErrorRecord(path, itemType);

            ThrowTerminatingError(er);
        }

        private static string NormalizePath(string path)
        {
            if (path.Length > 0)
            {
                char lastChar = path[path.Length - 1];

                if ((lastChar == '/') || (lastChar == '\\'))
                {
                    path = path.Substring(0, path.Length - 1);
                }

                string[] elts = GetPathElements(path);

                path = string.Join('\\', elts);
            }

            return path;
        }

        private static string[] GetPathElements(string path)
        {
            string[] allElts = path.Split(s_pathSeparators);
            string[] result = null;

            Stack<string> elts = new();

            foreach (string e in allElts)
            {
                if ((e == ".") || (e == string.Empty))
                {
                    continue;
                }
                else if (e == "..")
                {
                    if (elts.Count > 0)
                    {
                        elts.Pop();
                    }
                }
                else
                {
                    elts.Push(e);
                }
            }

            result = elts.ToArray();
            Array.Reverse(result);

            return result;
        }

        /// <summary>
        /// Delete private key.
        /// </summary>
        /// <param name="pProvInfo">Key prov info.</param>
        /// <returns>No return.</returns>
        [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Management.Automation.Security.NativeMethods.NCryptSetProperty(System.IntPtr,System.String,System.Void*,System.Int32,System.Int32)")]
        [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Management.Automation.Security.NativeMethods.NCryptFreeObject(System.IntPtr)")]
        private void DoDeleteKey(IntPtr pProvInfo)
        {
            IntPtr hProv = IntPtr.Zero;
            SMASecurity.NativeMethods.CRYPT_KEY_PROV_INFO keyProvInfo =
                Marshal.PtrToStructure<SMASecurity.NativeMethods.CRYPT_KEY_PROV_INFO>(pProvInfo);

            IntPtr hWnd = DetectUIHelper.GetOwnerWindow(Host);

            if (keyProvInfo.dwProvType != 0) // legacy
            {
                if (hWnd != IntPtr.Zero)
                {
                    if (SMASecurity.NativeMethods.CryptAcquireContext(
                        ref hProv,
                        keyProvInfo.pwszContainerName,
                        keyProvInfo.pwszProvName,
                        (int)keyProvInfo.dwProvType,
                        (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_VERIFYCONTEXT))
                    {
                        unsafe
                        {
                            void* pWnd = hWnd.ToPointer();
                            SMASecurity.NativeMethods.CryptSetProvParam(
                                hProv,
                                SMASecurity.NativeMethods.ProviderParam.PP_CLIENT_HWND,
                                &pWnd,
                                0);
                            SMASecurity.NativeMethods.CryptReleaseContext(hProv, 0);
                        }
                    }
                }

                if (!SMASecurity.NativeMethods.CryptAcquireContext(
                                ref hProv,
                                keyProvInfo.pwszContainerName,
                                keyProvInfo.pwszProvName,
                                (int)keyProvInfo.dwProvType,
                                keyProvInfo.dwFlags | (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_DELETEKEYSET |
                                (hWnd == IntPtr.Zero ? (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_SILENT : 0)))
                {
                    ThrowErrorRemoting(Marshal.GetLastWin32Error());
                }
            }
            else  // cng key
            {
                uint cngKeyFlag = 0;
                int result = 0;

                IntPtr hCNGProv = IntPtr.Zero;
                IntPtr hCNGKey = IntPtr.Zero;

                if ((keyProvInfo.dwFlags & (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_MACHINE_KEYSET) != 0)
                {
                    cngKeyFlag = (uint)SMASecurity.NativeMethods.NCryptDeletKeyFlag.NCRYPT_MACHINE_KEY_FLAG;
                }

                if (hWnd == IntPtr.Zero ||
                    (keyProvInfo.dwFlags & (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_SILENT) != 0)
                {
                    cngKeyFlag |= (uint)SMASecurity.NativeMethods.NCryptDeletKeyFlag.NCRYPT_SILENT_FLAG;
                }

                int stat = 0;
                try
                {
                    stat = SMASecurity.NativeMethods.NCryptOpenStorageProvider(
                                    ref hCNGProv,
                                    keyProvInfo.pwszProvName,
                                    0);
                    if (stat != 0)
                    {
                        ThrowErrorRemoting(stat);
                    }

                    stat = SMASecurity.NativeMethods.NCryptOpenKey(
                                        hCNGProv,
                                        ref hCNGKey,
                                        keyProvInfo.pwszContainerName,
                                        keyProvInfo.dwKeySpec,
                                        cngKeyFlag);
                    if (stat != 0)
                    {
                        ThrowErrorRemoting(stat);
                    }

                    if ((cngKeyFlag & (uint)SMASecurity.NativeMethods.NCryptDeletKeyFlag.NCRYPT_SILENT_FLAG) != 0)
                    {
                        unsafe
                        {
                            void* pWnd = hWnd.ToPointer();
                            SMASecurity.NativeMethods.NCryptSetProperty(
                                hCNGProv,
                                SMASecurity.NativeMethods.NCRYPT_WINDOW_HANDLE_PROPERTY,
                                &pWnd,
                                sizeof(void*),
                                0); // dwFlags
                        }
                    }

                    stat = SMASecurity.NativeMethods.NCryptDeleteKey(hCNGKey, 0);
                    if (stat != 0)
                    {
                        ThrowErrorRemoting(stat);
                    }

                    hCNGKey = IntPtr.Zero;
                }
                finally
                {
                    if (hCNGProv != IntPtr.Zero)
                        result = SMASecurity.NativeMethods.NCryptFreeObject(hCNGProv);

                    if (hCNGKey != IntPtr.Zero)
                        result = SMASecurity.NativeMethods.NCryptFreeObject(hCNGKey);
                }
            }
        }

        /// <summary>
        /// Delete the cert store; if -DeleteKey is specified, we also delete
        /// the associated private key.
        /// </summary>
        /// <param name="storeName">The store name.</param>
        /// <param name="fDeleteKey">Boolean to specify whether or not to delete private key.</param>
        /// <param name = "sourcePath">Source path.</param>
        /// <returns>No return.</returns>
        private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePath)
        {
            // if recurse is true, remove every cert in the store
            IntPtr localName = SMASecurity.NativeMethods.CryptFindLocalizedName(storeName);
            string[] pathElements = GetPathElements(sourcePath);
            if (localName == IntPtr.Zero)//not find, we can remove
            {
                X509NativeStore store = null;

                //
                // first open the store
                //
                store = GetStore(sourcePath, false, pathElements);
                store.Open(IncludeArchivedCerts());

                //
                // enumerate over each cert and remove it
                //
                IntPtr certContext = store.GetFirstCert();
                while (certContext != IntPtr.Zero)
                {
                    X509Certificate2 cert = new(certContext);
                    string certPath = sourcePath + cert.Thumbprint;
                    RemoveCertItem(cert, fDeleteKey, true, certPath);

                    certContext = store.GetNextCert(certContext);
                }
                // remove the cert store
                const SMASecurity.NativeMethods.CertOpenStoreFlags StoreFlags =
                        SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_READONLY_FLAG |
                        SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_OPEN_EXISTING_FLAG |
                        SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG |
                        SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_DELETE_FLAG |
                        SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE;

                // delete store
                IntPtr hCertStore = SMASecurity.NativeMethods.CertOpenStore(
                                SMASecurity.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM,
                                SMASecurity.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING,
                                IntPtr.Zero,  // hCryptProv
                                StoreFlags,
                                storeName);
            }
            else
            {
                string message = string.Format(
                                        CultureInfo.CurrentCulture,
                                        CertificateProviderStrings.RemoveStoreTemplate,
                                        storeName);
                const string errorId = "CannotRemoveSystemStore";
                ThrowInvalidOperation(errorId, message);
            }
        }
        /// <summary>
        /// Delete the a single cert from the store; if -DeleteKey is specified, we also delete
        /// the associated private key.
        /// </summary>
        /// <param name="cert">An X509Certificate2 object.</param>
        /// <param name="fDeleteKey">Boolean to specify whether or not to delete private key.</param>
        /// <param name="fMachine">Machine context or user.</param>
        /// <param name = "sourcePath">Source path.</param>
        /// <returns>No return.</returns>
        private void RemoveCertItem(X509Certificate2 cert, bool fDeleteKey, bool fMachine, string sourcePath)
        {
            if (cert != null)
            {
                string action = null;
                if (fDeleteKey)
                {
                    action = CertificateProviderStrings.Action_RemoveAndDeleteKey;
                }
                else
                {
                    action = CertificateProviderStrings.Action_Remove;
                }

                string resource = string.Format(
                                        CultureInfo.CurrentCulture,
                                        CertificateProviderStrings.RemoveItemTemplate,
                                        sourcePath);

                if (ShouldProcess(resource, action))
                {
                    DoRemove(cert, fDeleteKey, fMachine, sourcePath);
                }
            }
        }

        /// <summary>
        /// Delete the cert from the store; if -DeleteKey is specified, we also delete
        /// the associated private key.
        /// </summary>
        /// <param name="cert">An X509Certificate2 object.</param>
        /// <param name="fDeleteKey">Boolean to specify whether or not to delete private key.</param>
        /// <param name="fMachine">Machine context or user.</param>
        /// <param name = "sourcePath">Source path.</param>
        /// <returns>No return.</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults")]
        private void DoRemove(X509Certificate2 cert, bool fDeleteKey, bool fMachine, string sourcePath)
        {
            // get CERT_KEY_PROV_INFO_PROP_ID
            int provSize = 0;
            IntPtr pProvInfo = IntPtr.Zero;
            bool fHasPrivateKey = false;

            try
            {
                if (fDeleteKey)
                {
                    // it is fine if below call fails
                    if (SMASecurity.NativeMethods.CertGetCertificateContextProperty(
                                cert.Handle,
                                SMASecurity.NativeMethods.CertPropertyId.CERT_KEY_PROV_INFO_PROP_ID,
                                IntPtr.Zero,
                                ref provSize))
                    {
                        pProvInfo = Marshal.AllocHGlobal((int)provSize);

                        if (SMASecurity.NativeMethods.CertGetCertificateContextProperty(
                                cert.Handle,
                                SMASecurity.NativeMethods.CertPropertyId.CERT_KEY_PROV_INFO_PROP_ID,
                                pProvInfo,
                                ref provSize))
                        {
                            fHasPrivateKey = true;
                        }
                    }

                    if (!fHasPrivateKey)
                    {
                        // raise a verbose message
                        // we should not use WriteWarning here
                        string verboseNoPrivatekey = CertificateProviderStrings.VerboseNoPrivateKey;
                        WriteVerbose(verboseNoPrivatekey);
                    }
                }

                // do remove certificate
                // should not use the original handle

                if (!SMASecurity.NativeMethods.CertDeleteCertificateFromStore(
                            SMASecurity.NativeMethods.CertDuplicateCertificateContext(cert.Handle)))
                {
                    throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                }

                // commit the change to physical store
                if (sourcePath.Contains("UserDS"))
                {
                    SMASecurity.NativeMethods.CERT_CONTEXT context =
                        Marshal.PtrToStructure<SMASecurity.NativeMethods.CERT_CONTEXT>(cert.Handle);

                    CommitUserDS(context.hCertStore);
                }

                // TODO: Log Cert Delete

                // delete private key
                if (fDeleteKey && fHasPrivateKey)
                {
                    DoDeleteKey(pProvInfo);
                }
            }
            finally
            {
                if (pProvInfo != IntPtr.Zero)
                    Marshal.FreeHGlobal(pProvInfo);
            }
        }

        /// <summary>
        /// Commit store for UserDS store.
        /// </summary>
        /// <param name="storeHandle">An IntPtr for store handle.</param>
        /// <returns>No return.</returns>
        private static void CommitUserDS(IntPtr storeHandle)
        {
            if (!SMASecurity.NativeMethods.CertControlStore(
                                        storeHandle,
                                        0,
                                        SMASecurity.NativeMethods.CertControlStoreType.CERT_STORE_CTRL_COMMIT,
                                        IntPtr.Zero))
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }
        }

        /// <summary>
        /// Delete the cert from the original store and add to the destination store.
        /// </summary>
        /// <param name="destination">Destination path.</param>
        /// <param name="cert">An X509Certificate2.</param>
        /// <param name="store">An X509NativeStore.</param>
        /// <param name="sourcePath">Source path.</param>
        /// <returns>No return.</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults")]
        private void DoMove(string destination, X509Certificate2 cert, X509NativeStore store, string sourcePath)
        {
            IntPtr dupCert = IntPtr.Zero;  // should not free this
            IntPtr outCert = IntPtr.Zero;

            // duplicate cert first
            dupCert = SMASecurity.NativeMethods.CertDuplicateCertificateContext(cert.Handle);

            if (dupCert == IntPtr.Zero)
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }
            else
            {
                if (!SMASecurity.NativeMethods.CertAddCertificateContextToStore(
                                             store.StoreHandle,
                                             cert.Handle,
                                             (uint)SMASecurity.NativeMethods.AddCertificateContext.CERT_STORE_ADD_ALWAYS,
                                             ref outCert))
                {
                    throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                }

                if (!SMASecurity.NativeMethods.CertDeleteCertificateFromStore(dupCert))
                {
                    throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                }

                // TODO: log cert move
            }

            // commit the change to physical store
            if (destination.Contains("UserDS"))
            {
                CommitUserDS(store.StoreHandle);
            }

            if (sourcePath.Contains("UserDS"))
            {
                SMASecurity.NativeMethods.CERT_CONTEXT context = Marshal.PtrToStructure<SMASecurity.NativeMethods.CERT_CONTEXT>(cert.Handle);

                CommitUserDS(context.hCertStore);
            }

            // get the output object
            X509Certificate2 outObj = new(outCert);
            string certName = GetCertName(outObj);
            string certPath = MakePath(destination, certName);
            WriteItemObject((object)outObj, certPath, false);
        }

        /// <summary>
        /// Fetches the store-location/store/certificate at the
        /// specified path.
        /// </summary>
        /// <param name="path">Path to the item.</param>
        /// <param name="test">True if this is to only for an ItemExists call. Returns True / False.</param>
        /// <param name="isContainer">Set to true if item exists and is a container.</param>
        /// <returns>Item at the path.</returns>
        private object GetItemAtPath(string path, bool test, out bool isContainer)
        {
            Utils.CheckArgForNull(path, "path");

            object item = null;
            string[] pathElements = GetPathElements(path);

            //
            // certs have a fixed depth hierarchy.
            //
            // pathElements.Length == 0 ==> List<X509StoreLocation>
            // pathElements.Length == 1 ==> X509StoreLocation
            // pathElements.Length == 2 ==> X509NativeStore
            // pathElements.Length == 3 ==> X509Certificate2
            //
            // Thus lengths 1 & 2 are container items.
            //
            isContainer = pathElements.Length <= 2;

            X509NativeStore store = null;

            //
            // handle invalid path depth
            //
            if (pathElements.Length > 3)
            {
                if (test)
                {
                    return false;
                }
                else
                {
                    ThrowItemNotFound(path, CertificateProviderItem.Certificate);
                }
            }

            //
            // if path cache already has the item, return it
            //
            item = GetCachedItem(path);

            if (item == null)
            {
                switch (pathElements.Length)
                {
                    case 1:
                        // if this is a single element path and if we
                        // did not find in path-cache, the path
                        // must be wrong. This is because we initialize
                        // the only possible two store locations in ctor
                        if (test)
                        {
                            isContainer = false;
                            return false;
                        }
                        else
                        {
                            ThrowItemNotFound(path, CertificateProviderItem.StoreLocation);
                        }

                        break;

                    case 2:
                        //
                        // items at paths of depth 2 are stores.
                        //

                        //
                        // GetStore() handles store-not-found case. If Test is true,
                        // Item is True / False and we can return it.
                        //
                        store = GetStore(path, test, pathElements);
                        item = store;

                        break;

                    case 3:
                        //
                        // items at paths of depth 3 are certificates.
                        //
                        string storePath = GetParentPath(path, string.Empty);
                        string[] storePathElements = GetPathElements(storePath);

                        //
                        // first get the store
                        //

                        store = GetStore(storePath, false, storePathElements);

                        //
                        // store must be opened to get access to the
                        // certificates within it.
                        //

                        store.Open(IncludeArchivedCerts());

                        IntPtr certContext = store.GetCertByName(pathElements[2]);
                        if (certContext == IntPtr.Zero)
                        {
                            if (test)
                            {
                                return false;
                            }
                            else
                            {
                                ThrowItemNotFound(path, CertificateProviderItem.Certificate);
                            }
                        }

                        // Return true / false rather than the certificate
                        if (test)
                        {
                            item = true;
                        }
                        else
                        {
                            item = new X509Certificate2(certContext);
                        }

                        store.FreeCert(certContext);

                        break;

                    default:
                        // already handled by ThrowItemNotFound()
                        // at the beginning.
                        break;
                }
            }

            if ((item != null) && test)
            {
                item = true;
            }

            return item;
        }

        /// <summary>
        /// Gets the child items of a given store, or location.
        /// </summary>
        /// <param name="path">
        /// The full path of the store or location to enumerate.
        /// </param>
        /// <param name="recurse">
        /// If true, recursively enumerates the child items as well.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Path is null or empty.
        /// </exception>
        /// <exception cref="System.Security.Cryptography.CryptographicException">
        /// This exception can be thrown if any cryptographic error occurs.
        /// It is not possible to know exactly what went wrong.
        /// This is because of the way CryptographicException is designed.
        /// Possible reasons:
        ///  -- certificate is invalid
        ///  -- certificate has no private key
        ///  -- certificate password mismatch
        ///  -- etc
        /// </exception>
        protected override void GetChildItems(string path, bool recurse)
        {
            path = NormalizePath(path);

            GetChildItemsOrNames(path, recurse, ReturnContainers.ReturnAllContainers, false, GetFilter());
        }

        /// <summary>
        /// Gets the child names of a given store, or location.
        /// </summary>
        /// <param name="path">
        /// The full path of the store or location to enumerate.
        /// </param>
        /// <param name="returnContainers">
        /// Determines if all containers should be returned or only those containers that match the
        /// filter(s).
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Path is null or empty.
        /// </exception>
        /// <exception cref="System.Security.Cryptography.CryptographicException">
        /// This exception can be thrown if any cryptographic error occurs.
        /// It is not possible to know exactly what went wrong.
        /// This is because of the way CryptographicException is designed.
        /// Possible reasons:
        ///  -- certificate is invalid
        ///  -- certificate has no private key
        ///  -- certificate password mismatch
        ///  -- etc
        /// </exception>
        protected override void GetChildNames(
            string path,
            ReturnContainers returnContainers)
        {
            path = NormalizePath(path);
            GetChildItemsOrNames(path, false, returnContainers, true, GetFilter());
        }

        /// <summary>
        /// Determines if the item at the specified path is a store
        /// or location.
        /// </summary>
        /// <returns>
        /// True if the item at the specified path is a store or location.
        /// False otherwise.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// Path is null or empty.
        /// </exception>
        /// <exception cref="System.Security.Cryptography.CryptographicException">
        /// This exception can be thrown if any cryptographic error occurs.
        /// It is not possible to know exactly what went wrong.
        /// This is because of the way CryptographicException is designed.
        /// Possible reasons:
        ///  -- certificate is invalid
        ///  -- certificate has no private key
        ///  -- certificate password mismatch
        ///  -- etc
        /// </exception>
        protected override bool IsItemContainer(string path)
        {
            path = NormalizePath(path);
            Utils.CheckArgForNull(path, "path");
            bool isContainer = false;

            if (path.Length == 0)
            {
                //
                // root path is always container
                //
                isContainer = true;
            }
            else
            {
                //
                // We fetch the item to see if it is a container. This is
                // because the managed cert infrastructure does not
                // provide a way to test for existence.
                //
                GetItemAtPath(path, true, out isContainer);
            }

            s_tracer.WriteLine("result = {0}", isContainer);
            return isContainer;
        }

        /// <summary>
        /// Gets the dynamic parameters for get-item on the Certificate
        /// Provider.  We currently support the following dynamic parameters:
        /// "CodeSigning," that returns only certificates good for signing
        /// code or scripts.
        /// </summary>
        /// <param name="path">
        /// If the path was specified on the command line, this is the path
        /// to the item for which to get the dynamic parameters.
        /// </param>
        /// <returns>
        /// An object that has properties and fields decorated with
        /// parsing attributes similar to a cmdlet class.
        /// </returns>
        protected override object GetItemDynamicParameters(string path)
        {
            return new CertificateProviderDynamicParameters();
        }

        /// <summary>
        /// Gets the dynamic parameters for get-childitem on the Certificate
        /// Provider.  We currently only support one dynamic parameter,
        /// "CodeSigning," that returns only certificates good for signing
        /// code or scripts.
        /// </summary>
        /// <param name="path">
        /// If the path was specified on the command line, this is the path
        /// to the item for which to get the dynamic parameters.
        /// </param>
        /// <param name="recurse">
        /// Ignored.
        /// </param>
        /// <returns>
        /// An object that has properties and fields decorated with
        /// parsing attributes similar to a cmdlet class.
        /// </returns>
        protected override object GetChildItemsDynamicParameters(string path, bool recurse)
        {
            return new CertificateProviderDynamicParameters();
        }

        #endregion DriveCmdletProvider overrides

        #region private members

        /// <summary>
        /// Helper function to get store-location/store/cert at
        /// the specified path.
        /// </summary>
        /// <param name="path">Path to the item.</param>
        /// <param name="recurse">Whether we need to recursively find all.</param>
        /// <param name="returnContainers">
        /// Determines if all containers should be returned or only those containers that match the
        /// filter(s).
        /// </param>
        /// <param name="returnNames">Whether we only need the names.</param>
        /// <param name="filter">Filter info.</param>
        /// <returns> Does not return a value.</returns>
        private void GetChildItemsOrNames(
            string path,
            bool recurse,
            ReturnContainers returnContainers,
            bool returnNames,
            CertificateFilterInfo filter)
        {
            object thingToReturn = null;
            string childPath = null;

            bool returnAllContainers = returnContainers == ReturnContainers.ReturnAllContainers;

            Utils.CheckArgForNull(path, "path");

            //
            // children at the root path are store locations
            //
            if (path.Length == 0)
            {
                foreach (X509StoreLocation l in s_storeLocations)
                {
                    thingToReturn = returnNames ?
                        (object)l.LocationName : (object)l;

                    // 'returnNames' is true only when called from
                    // GetChildNames(), in which case 'recurse' will always be
                    // false.  When the -Path parameter needs to be globbed,
                    // the potential location names should be returned by
                    // calling this method from GetChildNames.

                    // The original code didn't have a "|| returnNames" clause.
                    // Suppose the user types:
                    //     dir cert:\curr* -CodeSigningCert -recurse
                    // We need to do path globbing here to resolve wild cards.
                    // Since -CodeSigningCert is present, 'filter' is not null.
                    // Since this method is called from GetChildNames() when
                    // doing the path globbing, 'returnNames' is true and
                    // 'recurse' is false.
                    // In the original code, nothing was returned by
                    // WriteItemObject(), so the path globbing fails and the
                    // above dir command would not display the certificates
                    // as expected.

                    // Another case is:
                    //     dir cert:\ -CodeSigningCert -Recurse
                    // -Recurse is present, so we need to call
                    // DoManualGetChildItems, and inside DoManualGetChildItems,
                    // this method will be called to get the names.
                    // The original code had the same problem for this case.

                    // With the "|| returnNames" clause, we test if this method
                    // is called from the GetChildNames().  When this method is
                    // called from GetChildNames(), 'recurse' will always be
                    // false.  Then we should return the names whether 'filter'
                    // is null or not.

                    if (filter == null || returnNames)
                    {
                        WriteItemObject(thingToReturn, l.LocationName, true);
                    }

                    childPath = l.LocationName;
                    if (recurse)
                    {
                        GetChildItemsOrNames(
                                        childPath,
                                        recurse,
                                        returnContainers,
                                        returnNames,
                                        filter);
                    }
                }
            }
            else
            {
                string[] pathElements = GetPathElements(path);

                //
                // children at depth 1 are stores
                //
                if (pathElements.Length == 1)
                {
                    GetStoresOrNames(pathElements[0],
                                     recurse,
                                     returnNames,
                                     filter);
                }
                //
                // children at depth 2 are certificates
                //
                else if (pathElements.Length == 2)
                {
                    GetCertificatesOrNames(path,
                                           pathElements,
                                           returnNames,
                                           filter);
                }
                else
                {
                    ThrowItemNotFound(path, CertificateProviderItem.Certificate);
                }
            }
        }

        /// <summary>
        /// Get the name of the specified certificate.
        /// </summary>
        /// <param name="cert"></param>
        /// <returns>Cert name .</returns>
        /// <remarks> we use Thumbprint as the name  </remarks>
        private static string GetCertName(X509Certificate2 cert)
        {
            return cert.Thumbprint;
        }

        /// <summary>
        /// Get cert objects or their name at the specified path.
        /// </summary>
        /// <param name="path">Path to cert.</param>
        /// <param name="pathElements">Path elements.</param>
        /// <param name="returnNames">Whether we should return only the names (instead of objects).</param>
        /// <param name="filter">Filter info.</param>
        /// <returns>Does not return a value.</returns>
        private void GetCertificatesOrNames(string path,
                                             string[] pathElements,
                                             bool returnNames,
                                             CertificateFilterInfo filter)
        {
            object thingToReturn = null;
            string certPath = null;
            X509NativeStore store = null;

            //
            // first open the store
            //

            store = GetStore(path, false, pathElements);
            store.Open(IncludeArchivedCerts());

            //
            // enumerate over each cert and return it (or its name)
            //
            IntPtr certContext = store.GetFirstCert();

            while (certContext != IntPtr.Zero)
            {
                X509Certificate2 cert = new(certContext);

                if (MatchesFilter(cert, filter))
                {
                    string certName = GetCertName(cert);
                    certPath = MakePath(path, certName);

                    if (returnNames)
                    {
                        thingToReturn = (object)certName;
                    }
                    else
                    {
                        PSObject myPsObj = new(cert);
                        thingToReturn = (object)myPsObj;
                    }

                    WriteItemObject(thingToReturn, certPath, false);
                }

                certContext = store.GetNextCert(certContext);
            }
        }

        /// <summary>
        /// Get X509StoreLocation object at path.
        /// </summary>
        /// <param name="path"></param>
        /// <returns>X509StoreLocation object.</returns>
        private X509StoreLocation GetStoreLocation(string path)
        {
            //
            // we store the only two possible store-location
            // objects during ctor.
            //
            X509StoreLocation location =
                GetCachedItem(path) as X509StoreLocation;

            if (location == null)
            {
                ThrowItemNotFound(path, CertificateProviderItem.StoreLocation);
            }

            return location;
        }

        /// <summary>
        /// Get the X509NativeStore object at path.
        /// </summary>
        /// <param name="path">Path to store.</param>
        /// <param name="test">True if this should be a test for path existence. Returns True or False.</param>
        /// <param name="pathElements">Path elements.</param>
        /// <returns>X509NativeStore object.</returns>
        private X509NativeStore GetStore(string path, bool test, string[] pathElements)
        {
            X509StoreLocation location = GetStoreLocation(pathElements[0]);
            X509NativeStore store = GetStore(path, pathElements[1], location);

            if (store == null)
            {
                if (test)
                {
                    return null;
                }
                else
                {
                    ThrowItemNotFound(path, CertificateProviderItem.Store);
                }
            }

            return store;
        }

        /// <summary>
        /// Gets the X509NativeStore at the specified path.
        /// Adds to cache if not already there.
        /// </summary>
        /// <param name="storePath">Path to the store.</param>
        /// <param name="storeName">Name of store (path leaf element).</param>
        /// <param name="storeLocation">Location of store (CurrentUser or LocalMachine).</param>
        /// <returns>X509NativeStore object.</returns>
        private X509NativeStore GetStore(string storePath,
                                   string storeName,
                                   X509StoreLocation storeLocation)
        {
            if (!storeLocation.StoreNames.ContainsKey(storeName))
            {
                ThrowItemNotFound(storePath, CertificateProviderItem.Store);
            }

            if (s_storeCache != null)
            {
                if (s_storeCache.Location != storeLocation ||
                    !string.Equals(
                                s_storeCache.StoreName,
                                storeName,
                                StringComparison.OrdinalIgnoreCase))
                {
                    s_storeCache = null;
                }
            }

            s_storeCache ??= new X509NativeStore(storeLocation, storeName);

            return s_storeCache;
        }

        /// <summary>
        /// Gets X509NativeStore objects or their name at the specified path.
        /// </summary>
        /// <param name="path">Path to the store.</param>
        /// <param name="recurse">Recursively return all items if true.</param>
        /// <param name="returnNames"></param>
        /// <param name="filter">Filter info.</param>
        /// <returns> Does not return a value.</returns>
        private void GetStoresOrNames(
            string path,
            bool recurse,
            bool returnNames,
            CertificateFilterInfo filter)
        {
            object thingToReturn = null;

            X509StoreLocation location = GetStoreLocation(path);

            string storePath = null;

            //
            // enumerate over each store
            //
            foreach (string name in location.StoreNames.Keys)
            {
                storePath = MakePath(path, name);
                if (returnNames)
                {
                    thingToReturn = name;
                }
                else
                {
                    X509NativeStore store = GetStore(storePath, name, location);
                    X509Store ManagedStore = new(store.StoreName, store.Location.Location);
                    thingToReturn = ManagedStore;
                }

                // 'returnNames' is true only when called from
                // GetChildNames(), in which case 'recurse' will always be
                // false.  When the -Path parameter needs to be globbed,
                // the potential store names should be returned by
                // calling this method from GetChildNames.

                // The original code didn't have a "|| returnNames" clause.
                // Suppose the user types:
                //     dir cert:\CurrentUser\Tru* -CodeSigningCert -recurse
                // We need to do path globbing here to resolve wild cards.
                // Since -CodeSigningCert is present, 'filter' is not null.
                // Since this method is called from GetChildNames() when
                // doing the path globbing, 'returnNames' is true and
                // 'recurse' is false.
                // In the original code, nothing was returned by
                // WriteItemObject(), so the path globbing fails and the
                // above dir command would not display the certificates
                // as expected.

                // Another case is:
                //     dir cert:\CurrentUser -CodeSigningCert -Recurse
                // -Recurse is present, so we need to call
                // DoManualGetChildItems, and inside DoManualGetChildItems,
                // this method will be called to get the names.
                // The original code had the same problem for this case.

                // With the "|| returnNames" clause, we test if this method
                // is called from the GetChildNames().  When this method is
                // called from GetChildNames(), 'recurse' will always be
                // false.  Then we should return the names whether 'filter'
                // is null or not.

                if (filter == null || returnNames)
                {
                    WriteItemObject(thingToReturn, name, true);
                }

                //
                // if recurse is true, get cert objects (or names) as well
                //
                if (recurse)
                {
                    string[] pathElements = GetPathElements(storePath);
                    GetCertificatesOrNames(
                                    storePath,
                                    pathElements,
                                    returnNames,
                                    filter);
                }
            }
        }

        private CertificateFilterInfo GetFilter()
        {
            CertificateFilterInfo filter = null;

            if (DynamicParameters != null && DynamicParameters is CertificateProviderDynamicParameters dp)
            {
                if (dp.CodeSigningCert)
                {
                    filter = new CertificateFilterInfo();
                    filter.Purpose = CertificatePurpose.CodeSigning;
                }

                if (dp.DocumentEncryptionCert)
                {
                    filter ??= new CertificateFilterInfo();
                    filter.Purpose = CertificatePurpose.DocumentEncryption;
                }

                if (dp.DnsName != null)
                {
                    filter ??= new CertificateFilterInfo();
                    filter.DnsName = new WildcardPattern(dp.DnsName, WildcardOptions.IgnoreCase);
                }

                if (dp.Eku != null)
                {
                    filter ??= new CertificateFilterInfo();
                    filter.Eku = new List<WildcardPattern>();
                    foreach (var pattern in dp.Eku)
                    {
                        filter.Eku.Add(new WildcardPattern(pattern, WildcardOptions.IgnoreCase));
                    }
                }

                if (dp.ExpiringInDays >= 0)
                {
                    filter ??= new CertificateFilterInfo();
                    filter.Expiring = DateTime.Now.AddDays(dp.ExpiringInDays);
                }

                if (dp.SSLServerAuthentication)
                {
                    filter ??= new CertificateFilterInfo();
                    filter.SSLServerAuthentication = true;
                }
            }

            return filter;
        }

        private bool IncludeArchivedCerts()
        {
            bool includeArchivedCerts = false;

            if (Force)
            {
                includeArchivedCerts = true;
            }

            return includeArchivedCerts;
        }

        private static bool MatchesFilter(X509Certificate2 cert, CertificateFilterInfo filter)
        {
            // No filter means, match everything
            if (filter == null)
            {
                return true;
            }

            if (filter.Expiring > DateTime.MinValue && !SecuritySupport.CertExpiresByTime(cert, filter.Expiring))
            {
                return false;
            }

            if (filter.DnsName != null && !CertContainsName(cert, filter.DnsName))
            {
                return false;
            }

            if (filter.Eku != null && !CertContainsEku(cert, filter.Eku))
            {
                return false;
            }

            if (filter.SSLServerAuthentication && !CertIsSSLServerAuthentication(cert))
            {
                return false;
            }

            switch (filter.Purpose)
            {
                case CertificatePurpose.CodeSigning:
                    return SecuritySupport.CertIsGoodForSigning(cert);

                case CertificatePurpose.DocumentEncryption:
                    return SecuritySupport.CertIsGoodForEncryption(cert);

                case CertificatePurpose.NotSpecified:
                case CertificatePurpose.All:
                    return true;

                default:
                    break;
            }

            return false;
        }

        /// <summary>
        /// Check if the specified certificate has the name in DNS name list.
        /// </summary>
        /// <param name="cert">Certificate object.</param>
        /// <param name="pattern">Wildcard pattern for DNS name to search.</param>
        /// <returns>True on success, false otherwise.</returns>
        internal static bool CertContainsName(X509Certificate2 cert, WildcardPattern pattern)
        {
            List<DnsNameRepresentation> list = (new DnsNameProperty(cert)).DnsNameList;
            foreach (DnsNameRepresentation dnsName in list)
            {
                if (pattern.IsMatch(dnsName.Unicode))
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Check if the specified certificate is a server authentication certificate.
        /// </summary>
        /// <param name="cert">Certificate object.</param>
        /// <returns>True on success, false otherwise.</returns>
        internal static bool CertIsSSLServerAuthentication(X509Certificate2 cert)
        {
            X509ExtensionCollection extentionList = cert.Extensions;
            foreach (var extension in extentionList)
            {
                if (extension is X509EnhancedKeyUsageExtension eku)
                {
                    foreach (Oid usage in eku.EnhancedKeyUsages)
                    {
                        if (usage.Value.Equals(CertificateFilterInfo.OID_PKIX_KP_SERVER_AUTH, StringComparison.Ordinal))
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// Check if the specified certificate contains EKU matching all of these patterns.
        /// </summary>
        /// <param name="cert">Certificate object.</param>
        /// <param name="ekuPatterns">EKU patterns.</param>
        /// <returns>True on success, false otherwise.</returns>
        internal static bool CertContainsEku(X509Certificate2 cert, List<WildcardPattern> ekuPatterns)
        {
            X509ExtensionCollection extensionList = cert.Extensions;
            foreach (var extension in extensionList)
            {
                if (extension is X509EnhancedKeyUsageExtension eku)
                {
                    OidCollection enhancedKeyUsages = eku.EnhancedKeyUsages;
                    foreach (WildcardPattern ekuPattern in ekuPatterns)
                    {
                        const bool patternPassed = false;
                        foreach (var usage in enhancedKeyUsages)
                        {
                            if (ekuPattern.IsMatch(usage.Value) || ekuPattern.IsMatch(usage.FriendlyName))
                            {
                                return true;
                            }
                        }

                        if (!patternPassed)
                        {
                            return false;
                        }
                    }

                    return true;
                }
            }

            return false;
        }

        private static object GetCachedItem(string path)
        {
            object item = null;

            lock (s_staticLock)
            {
                if (s_pathCache.ContainsKey(path))
                {
                    item = s_pathCache[path];
                    Dbg.Diagnostics.Assert(item != null, "GetCachedItem");
                }
            }

            return item;
        }

        private static void AddItemToCache(string path, object item)
        {
            lock (s_staticLock)
            {
                if ((item != null) && (!s_pathCache.ContainsKey(path)))
                {
                    s_pathCache.Add(path, item);
                }
            }
        }

        #endregion private members

        #region ICmdletProviderSupportsHelp Members

        /// <summary>
        /// Get provider-specific help.
        /// </summary>
        /// <param name="helpItemName">
        /// Name of help item or cmdlet for which user has requested help
        /// </param>
        /// <param name = "path">
        /// Path to the current location or path to the location of the property that the user needs
        /// help about.
        /// </param>
        /// <returns>
        /// Provider specific MAML help content string
        /// </returns>
        string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path)
        {
            //
            // Get the ver and noun from helpItemName
            //
            string verb = null;
            string noun = null;
            try
            {
                if (!string.IsNullOrEmpty(helpItemName))
                {
                    CmdletInfo.SplitCmdletName(helpItemName, out verb, out noun);
                }
                else
                {
                    return string.Empty;
                }

                if (string.IsNullOrEmpty(verb) || string.IsNullOrEmpty(noun))
                {
                    return string.Empty;
                }

                //
                // Load the help file from the current UI culture subfolder of the module's root folder
                //
                XmlDocument document = new();

                CultureInfo currentUICulture = CultureInfo.CurrentUICulture;

                string fullHelpPath = Path.Combine(
                    this.ProviderInfo.ApplicationBase,
                    currentUICulture.ToString(),
                    this.ProviderInfo.HelpFile);
                XmlReaderSettings settings = new();
                settings.XmlResolver = null;
                using (XmlReader reader = XmlReader.Create(fullHelpPath, settings))
                {
                    document.Load(reader);
                }

                // Add "msh" and "command" namespaces from the MAML schema
                XmlNamespaceManager nsMgr = new(document.NameTable);
                nsMgr.AddNamespace("msh", HelpCommentsParser.mshURI);
                nsMgr.AddNamespace("command", HelpCommentsParser.commandURI);

                // Compose XPath query to select the appropriate node based on the cmdlet
                string xpathQuery = string.Format(
                    CultureInfo.InvariantCulture,
                    HelpCommentsParser.ProviderHelpCommandXPath,
                    string.Empty,
                    verb,
                    noun);

                // Execute the XPath query and return its MAML snippet
                XmlNode result = document.SelectSingleNode(xpathQuery, nsMgr);
                if (result != null)
                {
                    return result.OuterXml;
                }
            }
            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;
            }
            catch (XPathException)
            {
                return string.Empty;
            }

            return string.Empty;
        }

        #endregion
    }

    /// <summary>
    /// Defines a class to represent a store location in the certificate
    /// provider.  The two possible store locations are CurrentUser and
    /// LocalMachine.
    /// </summary>
    public sealed class X509StoreLocation
    {
        /// <summary>
        /// Gets the location, as a string.
        /// </summary>
        public string LocationName
        {
            get
            {
                return _location.ToString();
            }
        }

        /// <summary>
        /// Gets the location as a
        /// <see cref="System.Security.Cryptography.X509Certificates.StoreLocation"/>
        /// </summary>
        public StoreLocation Location
        {
            get
            {
                return _location;
            }

            set
            {
                _location = value;
            }
        }

        private StoreLocation _location = StoreLocation.CurrentUser;

        /// <summary>
        /// Gets the list of stores at this location.
        /// </summary>
        public Hashtable StoreNames
        {
            get
            {
                Hashtable storeNames;
                // always try to get new names
                storeNames = new Hashtable(StringComparer.OrdinalIgnoreCase);

                // since there is no managed support to obtain store names,
                // we use pinvoke to get it ourselves.
                List<string> names = Crypt32Helpers.GetStoreNamesAtLocation(_location);
                foreach (string name in names)
                {
                    storeNames.Add(name, true);
                }

                return storeNames;
            }
        }

        /// <summary>
        /// Initializes a new instance of the X509StoreLocation class.
        /// </summary>
        public X509StoreLocation(StoreLocation location)
        {
            Location = location;
        }
    }

    /// <summary>
    /// Defines the type of EKU string
    /// The structure contains friendly name and EKU oid.
    /// </summary>
    [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
    public readonly struct EnhancedKeyUsageRepresentation
    {
        /// <summary>
        /// Localized friendly name of EKU.
        /// </summary>
        private readonly string _friendlyName;

        /// <summary>
        /// OID of EKU.
        /// </summary>
        private readonly string _oid;

        /// <summary>
        /// Constructor of an EnhancedKeyUsageRepresentation.
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Oid")]

        public EnhancedKeyUsageRepresentation(string inputFriendlyName, string inputOid)
        {
            _friendlyName = inputFriendlyName;
            _oid = inputOid;
        }

        /// <summary>
        /// Value comparison.
        /// </summary>
        public bool Equals(EnhancedKeyUsageRepresentation keyUsage)
        {
            bool match = false;

            if (_oid != null && keyUsage._oid != null)
            {
                // OID strings only contain numbers and periods

                if (string.Equals(_oid, keyUsage._oid, StringComparison.Ordinal))
                {
                    match = true;
                }
            }
            else if (_oid == null && keyUsage._oid == null)
            {
                match = true;
            }

            return match;
        }

        /// <summary>
        /// Get property of friendlyName.
        /// </summary>
        public string FriendlyName
        {
            get
            {
                return _friendlyName;
            }
        }

        /// <summary>
        /// Get property of oid.
        /// </summary>
        public string ObjectId
        {
            get
            {
                return _oid;
            }
        }

        /// <summary>
        /// Get display string.
        /// </summary>
        public override string ToString()
        {
            return string.IsNullOrEmpty(_friendlyName) ?
                        _oid :
                        _friendlyName + " (" + _oid + ")";
        }
    }

    /// <summary>
    /// Class for SendAsTrustedIssuer.
    /// </summary>
    [SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors")]
    public sealed class SendAsTrustedIssuerProperty
    {
        /// <summary>
        /// Get property of SendAsTrustedIssuer.
        /// </summary>
        [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
        public static bool ReadSendAsTrustedIssuerProperty(X509Certificate2 cert)
        {
            bool fHasProperty = false;
            if (DownLevelHelper.TrustedIssuerSupported())
            {
                int propSize = 0;
                // try to get the property
                // it is fine if fail for not there
                if (SMASecurity.NativeMethods.CertGetCertificateContextProperty(
                                cert.Handle,
                                SMASecurity.NativeMethods.CertPropertyId.CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID,
                                IntPtr.Zero,
                                ref propSize))
                {
                    // we have the property
                    fHasProperty = true;
                }
                else
                {
                    // if fail
                    int error = Marshal.GetLastWin32Error();
                    if (error != SMASecurity.NativeMethods.CRYPT_E_NOT_FOUND)
                    {
                        throw new System.ComponentModel.Win32Exception(error);
                    }
                }
            }

            return fHasProperty;
        }

        /// <summary>
        /// Set property of SendAsTrustedIssuer.
        /// </summary>
        [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
        public static void WriteSendAsTrustedIssuerProperty(X509Certificate2 cert, string certPath, bool addProperty)
        {
            if (DownLevelHelper.TrustedIssuerSupported())
            {
                IntPtr propertyPtr = IntPtr.Zero;
                SMASecurity.NativeMethods.CRYPT_DATA_BLOB dataBlob = new();
                dataBlob.cbData = 0;
                dataBlob.pbData = IntPtr.Zero;
                X509Certificate certFromStore = null;

                try
                {
                    if (certPath != null)
                    {
                        // try to open the store and get the cert out
                        // in case the store handle is already released
                        string[] pathElements = GetPathElements(certPath);

                        // certpath is in the format: Microsoft.Powershell.Security\
                        // Certificate::CurrentUser(LocalMachine)\my\HashID
                        // obtained pathElements[0] is Microsoft.Powershell.Security
                        // obtained pathElements[1] is Certificate::CurrentUser
                        // obtained pathElements[2] is MY
                        // obtained pathElements[3] is HashID

                        bool fUserContext = string.Equals(pathElements[1], "Certificate::CurrentUser", StringComparison.OrdinalIgnoreCase);

                        X509StoreLocation storeLocation =
                            new(fUserContext ? StoreLocation.CurrentUser : StoreLocation.LocalMachine);

                        // get certificate from the store pathElements[2]
                        X509NativeStore store = null;

                        store = new X509NativeStore(storeLocation, pathElements[2]);
                        store.Open(true); // including archival flag

                        IntPtr certContext = store.GetCertByName(pathElements[3]);

                        if (certContext != IntPtr.Zero)
                        {
                            certFromStore = new X509Certificate2(certContext);
                            store.FreeCert(certContext);
                        }
                    }

                    if (addProperty) // should add the property
                    {
                        propertyPtr = Marshal.AllocHGlobal(Marshal.SizeOf(dataBlob));
                        Marshal.StructureToPtr(dataBlob, propertyPtr, false);
                    }

                    // set property
                    if (!SMASecurity.NativeMethods.CertSetCertificateContextProperty(
                                certFromStore != null ? certFromStore.Handle : cert.Handle,
                                SMASecurity.NativeMethods.CertPropertyId.CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID,
                                0,
                                propertyPtr))
                    {
                        throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                finally
                {
                    if (propertyPtr != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(propertyPtr);
                    }
                }
            }
            else
            {
                Marshal.ThrowExceptionForHR(SMASecurity.NativeMethods.NTE_NOT_SUPPORTED);
            }
        }

        private static readonly char[] s_separators = new char[] { '/', '\\' };

        private static string[] GetPathElements(string path)
        {
            string[] allElts = path.Split(s_separators);
            string[] result = null;

            Stack<string> elts = new();

            foreach (string e in allElts)
            {
                if ((e == ".") || (e == string.Empty))
                {
                    continue;
                }
                else if (e == "..")
                {
                    if (elts.Count > 0)
                    {
                        elts.Pop();
                    }
                }
                else
                {
                    elts.Push(e);
                }
            }

            result = elts.ToArray();
            Array.Reverse(result);

            return result;
        }
    }
    /// <summary>
    /// Class for ekulist.
    /// </summary>
    public sealed class EnhancedKeyUsageProperty
    {
        private readonly List<EnhancedKeyUsageRepresentation> _ekuList = new();

        /// <summary>
        /// Get property of EKUList.
        /// </summary>
        public List<EnhancedKeyUsageRepresentation> EnhancedKeyUsageList
        {
            get
            {
                return _ekuList;
            }
        }

        /// <summary>
        /// Constructor for EnhancedKeyUsageProperty.
        /// </summary>
        public EnhancedKeyUsageProperty(X509Certificate2 cert)
        {
            foreach (X509Extension extension in cert.Extensions)
            {
                // Filter to the OID for EKU
                if (extension.Oid.Value == "2.5.29.37" && extension is X509EnhancedKeyUsageExtension ext)
                {
                    OidCollection oids = ext.EnhancedKeyUsages;
                    foreach (Oid oid in oids)
                    {
                        EnhancedKeyUsageRepresentation ekuString = new(oid.FriendlyName, oid.Value);
                        _ekuList.Add(ekuString);
                    }
                }
            }
        }
    }

    /// <summary>
    /// Class for DNSNameList.
    /// </summary>
    public sealed class DnsNameProperty
    {
        private readonly List<DnsNameRepresentation> _dnsList = new();
        private readonly IdnMapping idnMapping = new();

        private const string distinguishedNamePrefix = "CN=";

        /// <summary>
        /// Get property of DnsNameList.
        /// </summary>
        public List<DnsNameRepresentation> DnsNameList => _dnsList;

        private DnsNameRepresentation GetDnsNameRepresentation(string dnsName)
        {
            string unicodeName;

            try
            {
                unicodeName = idnMapping.GetUnicode(dnsName);
            }
            catch (ArgumentException)
            {
                // The name is not valid Punycode, assume it's valid ASCII.
                unicodeName = dnsName;
            }

            return new DnsNameRepresentation(dnsName, unicodeName);
        }

        /// <summary>
        /// Constructor for DnsNameProperty.
        /// </summary>
        public DnsNameProperty(X509Certificate2 cert)
        {
            _dnsList = new List<DnsNameRepresentation>();

            // extract DNS name from subject distinguish name
            // if it exists and does not contain a comma
            // a comma, indicates it is not a DNS name
            if (cert.Subject.StartsWith(distinguishedNamePrefix, StringComparison.OrdinalIgnoreCase) &&
                !cert.Subject.Contains(','))
            {
                string parsedSubjectDistinguishedDnsName = cert.Subject.Substring(distinguishedNamePrefix.Length);
                DnsNameRepresentation dnsName = GetDnsNameRepresentation(parsedSubjectDistinguishedDnsName);
                _dnsList.Add(dnsName);
            }

            // Extract DNS names from SAN extensions
            foreach (X509Extension extension in cert.Extensions)
            {
                if (extension is X509SubjectAlternativeNameExtension sanExtension)
                {
                    foreach (string dnsNameEntry in sanExtension.EnumerateDnsNames())
                    {
                        DnsNameRepresentation dnsName = GetDnsNameRepresentation(dnsNameEntry);

                        // Only add the name if it is not the same as an existing name.
                        if (!_dnsList.Contains(dnsName))
                        {
                            _dnsList.Add(dnsName);
                        }
                    }
                }
            }
        }
    }

    /// <summary>
    /// Downlevel helper function to determine if the OS is WIN8 and above.
    /// </summary>
    internal static class DownLevelHelper
    {
        private static bool s_isWin8Set = false;
        private static bool s_isWin8 = false;

        internal static bool IsWin8AndAbove()
        {
            if (!s_isWin8Set)
            {
                System.OperatingSystem osInfo = System.Environment.OSVersion;
                PlatformID platform = osInfo.Platform;
                Version version = osInfo.Version;

                if (platform.Equals(PlatformID.Win32NT) &&
                    ((version.Major > 6) ||
                     (version.Major == 6 && version.Minor >= 2)))
                {
                    s_isWin8 = true;
                }

                s_isWin8Set = true;
            }

            return s_isWin8;
        }

        internal static bool TrustedIssuerSupported()
        {
            return IsWin8AndAbove();
        }

        internal static bool HashLookupSupported()
        {
            return IsWin8AndAbove();
        }
    }

    /// <summary>
    /// Check in UI is allowed.
    /// </summary>
    internal static class DetectUIHelper
    {
#if CORECLR
        internal static IntPtr GetOwnerWindow(PSHost host)
        {
            return IntPtr.Zero;
        }
#else
        private static IntPtr hWnd = IntPtr.Zero;
        private static bool firstRun = true;

        internal static IntPtr GetOwnerWindow(PSHost host)
        {
            if (firstRun)
            {
                firstRun = false;

                if (IsUIAllowed(host))
                {
                    hWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;

                    if (hWnd == IntPtr.Zero)
                    {
                        hWnd = SMASecurity.NativeMethods.GetConsoleWindow();
                    }

                    if (hWnd == IntPtr.Zero)
                    {
                        hWnd = SMASecurity.NativeMethods.GetDesktopWindow();
                    }
                }
            }

            return hWnd;
        }

        private static bool IsUIAllowed(PSHost host)
        {
            if (host.Name.Equals("ServerRemoteHost", StringComparison.OrdinalIgnoreCase))
                return false;

            uint SessionId;
            if (!SMASecurity.NativeMethods.ProcessIdToSessionId((uint)Environment.ProcessId, out SessionId))
                return false;

            if (SessionId == 0)
                return false;

            if (!Environment.UserInteractive)
                return false;

            string[] args = Environment.GetCommandLineArgs();

            bool fRet = true;
            foreach (string arg in args)
            {
                const string NonInteractiveParamName = "-noninteractive";
                if (arg.Length >= 4 && NonInteractiveParamName.StartsWith(arg, StringComparison.OrdinalIgnoreCase))
                {
                    fRet = false;
                    break;
                }
            }

            return fRet;
        }
#endif
    }

    /// <summary>
    /// Container for helper functions that use pinvoke into crypt32.dll.
    /// </summary>
    internal static class Crypt32Helpers
    {
        /// <summary>
        /// Lock that guards access to the following static members
        /// -- storeNames.
        /// </summary>
        private static readonly object s_staticLock = new();

        internal static readonly List<string> storeNames = new();

        /// <summary>
        /// Get a list of store names at the specified location.
        /// </summary>
        internal static List<string> GetStoreNamesAtLocation(StoreLocation location)
        {
            SMASecurity.NativeMethods.CertStoreFlags locationFlag =
                SMASecurity.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER;

            switch (location)
            {
                case StoreLocation.CurrentUser:
                    locationFlag = SMASecurity.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER;
                    break;

                case StoreLocation.LocalMachine:
                    locationFlag = SMASecurity.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE;
                    break;

                default:
                    Diagnostics.Assert(false, "GetStoreNamesAtLocation: invalid location value");
                    break;
            }

            SMASecurity.NativeMethods.CertEnumSystemStoreCallBackProto callBack = new(CertEnumSystemStoreCallBack);

            // Return a new list to avoid synchronization issues.

            List<string> names = new();
            lock (s_staticLock)
            {
                storeNames.Clear();

                SMASecurity.NativeMethods.CertEnumSystemStore(locationFlag, IntPtr.Zero,
                                                  IntPtr.Zero, callBack);
                foreach (string name in storeNames)
                {
                    names.Add(name);
                }
            }

            return names;
        }

        /// <summary>
        /// Call back function used by CertEnumSystemStore
        ///
        /// Currently, there is no managed support for enumerating store
        /// names on a machine. We use the win32 function CertEnumSystemStore()
        /// to get a list of stores for a given context.
        ///
        /// Each time this callback is called, we add the passed store name
        /// to the list of stores.
        /// </summary>
        internal static bool CertEnumSystemStoreCallBack(string storeName,
                                                          DWORD dwFlagsNotUsed,
                                                          IntPtr notUsed1,
                                                          IntPtr notUsed2,
                                                          IntPtr notUsed3)
        {
            storeNames.Add(storeName);
            return true;
        }
    }
}
#endif // !UNIX