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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#nullable enable

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Configuration;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Security;
using System.Text;

using Dbg = System.Management.Automation.Diagnostics;

namespace Microsoft.PowerShell
{
    /// <summary>
    /// Null class implementation of PSHostUserInterface used when no console is available and when PowerShell
    /// is run in servmode where no console is needed.
    /// </summary>
    internal class NullHostUserInterface : PSHostUserInterface
    {
        /// <summary>
        /// RawUI.
        /// </summary>
        public override PSHostRawUserInterface? RawUI
            => null;

        /// <summary>
        /// Prompt.
        /// </summary>
        /// <param name="caption"></param>
        /// <param name="message"></param>
        /// <param name="descriptions"></param>
        /// <returns></returns>
        public override Dictionary<string, PSObject> Prompt(string caption, string message, Collection<FieldDescription> descriptions)
            => throw new PSNotImplementedException();

        /// <summary>
        /// PromptForChoice.
        /// </summary>
        /// <param name="caption"></param>
        /// <param name="message"></param>
        /// <param name="choices"></param>
        /// <param name="defaultChoice"></param>
        /// <returns></returns>
        public override int PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, int defaultChoice)
            => throw new PSNotImplementedException();

        /// <summary>
        /// PromptForCredential.
        /// </summary>
        /// <param name="caption"></param>
        /// <param name="message"></param>
        /// <param name="userName"></param>
        /// <param name="targetName"></param>
        /// <returns></returns>
        public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName)
            => throw new PSNotImplementedException();

        /// <summary>
        /// PromptForCredential.
        /// </summary>
        /// <param name="caption"></param>
        /// <param name="message"></param>
        /// <param name="userName"></param>
        /// <param name="targetName"></param>
        /// <param name="allowedCredentialTypes"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
            => throw new PSNotImplementedException();

        /// <summary>
        /// ReadLine.
        /// </summary>
        /// <returns></returns>
        public override string ReadLine()
            => throw new PSNotImplementedException();

        /// <summary>
        /// ReadLineAsSecureString.
        /// </summary>
        /// <returns></returns>
        public override SecureString ReadLineAsSecureString()
            => throw new PSNotImplementedException();

        /// <summary>
        /// Write.
        /// </summary>
        /// <param name="value"></param>
        public override void Write(string value)
        { }

        /// <summary>
        /// Write.
        /// </summary>
        /// <param name="foregroundColor"></param>
        /// <param name="backgroundColor"></param>
        /// <param name="value"></param>
        public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
        { }

        /// <summary>
        /// WriteDebugLine.
        /// </summary>
        /// <param name="message"></param>
        public override void WriteDebugLine(string message)
        { }

        /// <summary>
        /// WriteErrorLine.
        /// </summary>
        /// <param name="value"></param>
        public override void WriteErrorLine(string value)
            => Console.Out.WriteLine(value);

        /// <summary>
        /// WriteLine.
        /// </summary>
        /// <param name="value"></param>
        public override void WriteLine(string value)
        { }

        /// <summary>
        /// WriteProgress.
        /// </summary>
        /// <param name="sourceId"></param>
        /// <param name="record"></param>
        public override void WriteProgress(long sourceId, ProgressRecord record)
        { }

        /// <summary>
        /// WriteVerboseLine.
        /// </summary>
        /// <param name="message"></param>
        public override void WriteVerboseLine(string message)
        { }

        /// <summary>
        /// WriteWarningLine.
        /// </summary>
        /// <param name="message"></param>
        public override void WriteWarningLine(string message)
        { }
    }

    internal class CommandLineParameterParser
    {
        private const int MaxPipePathLengthLinux = 108;
        private const int MaxPipePathLengthMacOS = 104;

        internal static int MaxNameLength()
        {
            if (Platform.IsWindows)
            {
                return ushort.MaxValue;
            }

            int maxLength = Platform.IsLinux ? MaxPipePathLengthLinux : MaxPipePathLengthMacOS;
            return maxLength - Path.GetTempPath().Length;
        }

        internal bool? InputRedirectedTestHook;

        private static readonly string[] s_validParameters = {
            "sta",
            "mta",
            "command",
            "commandwithargs",
            "configurationname",
            "custompipename",
            "encodedcommand",
            "executionpolicy",
            "file",
            "help",
            "inputformat",
            "login",
            "noexit",
            "nologo",
            "noninteractive",
            "noprofile",
            "noprofileloadtime",
            "outputformat",
            "removeworkingdirectorytrailingcharacter",
            "settingsfile",
            "version",
            "windowstyle",
            "workingdirectory"
        };

#pragma warning disable SA1025 // CodeMustNotContainMultipleWhitespaceInARow
        /// <summary>
        /// These represent the parameters that are used when starting pwsh.
        /// We can query in our telemetry to determine how pwsh was invoked.
        /// </summary>
        [Flags]
        internal enum ParameterBitmap : long
        {
            Command             = 0x0000000000000001, // -Command | -c
            ConfigurationName   = 0x0000000000000002, // -ConfigurationName | -config
            CustomPipeName      = 0x0000000000000004, // -CustomPipeName
            EncodedCommand      = 0x0000000000000008, // -EncodedCommand | -e | -ec
            EncodedArgument     = 0x0000000000000010, // -EncodedArgument
            ExecutionPolicy     = 0x0000000000000020, // -ExecutionPolicy | -ex | -ep
            File                = 0x0000000000000040, // -File | -f
            Help                = 0x0000000000000080, // -Help, -?, /?
            InputFormat         = 0x0000000000000100, // -InputFormat | -inp | -if
            Interactive         = 0x0000000000000200, // -Interactive | -i
            Login               = 0x0000000000000400, // -Login | -l
            MTA                 = 0x0000000000000800, // -MTA
            NoExit              = 0x0000000000001000, // -NoExit | -noe
            NoLogo              = 0x0000000000002000, // -NoLogo | -nol
            NonInteractive      = 0x0000000000004000, // -NonInteractive | -noni
            NoProfile           = 0x0000000000008000, // -NoProfile | -nop
            OutputFormat        = 0x0000000000010000, // -OutputFormat | -o | -of
            SettingsFile        = 0x0000000000020000, // -SettingsFile | -settings
            SSHServerMode       = 0x0000000000040000, // -SSHServerMode | -sshs
            SocketServerMode    = 0x0000000000080000, // -SocketServerMode | -sockets
            ServerMode          = 0x0000000000100000, // -ServerMode | -server
            NamedPipeServerMode = 0x0000000000200000, // -NamedPipeServerMode | -namedpipes
            STA                 = 0x0000000000400000, // -STA
            Version             = 0x0000000000800000, // -Version | -v
            WindowStyle         = 0x0000000001000000, // -WindowStyle | -w
            WorkingDirectory    = 0x0000000002000000, // -WorkingDirectory | -wd
            ConfigurationFile   = 0x0000000004000000, // -ConfigurationFile
            NoProfileLoadTime   = 0x0000000008000000, // -NoProfileLoadTime
            CommandWithArgs     = 0x0000000010000000, // -CommandWithArgs | -cwa

            // Enum values for specified ExecutionPolicy
            EPUnrestricted      = 0x0000000100000000, // ExecutionPolicy unrestricted
            EPRemoteSigned      = 0x0000000200000000, // ExecutionPolicy remote signed
            EPAllSigned         = 0x0000000400000000, // ExecutionPolicy all signed
            EPRestricted        = 0x0000000800000000, // ExecutionPolicy restricted
            EPDefault           = 0x0000001000000000, // ExecutionPolicy default
            EPBypass            = 0x0000002000000000, // ExecutionPolicy bypass
            EPUndefined         = 0x0000004000000000, // ExecutionPolicy undefined
            EPIncorrect         = 0x0000008000000000, // ExecutionPolicy incorrect

            // V2 Socket Server Mode
            V2SocketServerMode  = 0x0000100000000000, // -V2SocketServerMode | -v2so
        }
#pragma warning restore SA1025 // CodeMustNotContainMultipleWhitespaceInARow

        internal ParameterBitmap ParametersUsed = 0;

        internal double ParametersUsedAsDouble
        {
            get { return (double)ParametersUsed; }
        }

        [Conditional("DEBUG")]
        private void AssertArgumentsParsed()
        {
            if (!_dirty)
            {
                throw new InvalidOperationException("Parse has not been called yet");
            }
        }

        internal CommandLineParameterParser()
        {
        }

        #region Internal properties

        internal bool AbortStartup
        {
            get
            {
                AssertArgumentsParsed();
                return _abortStartup;
            }
        }

        internal string? SettingsFile
        {
            get
            {
                AssertArgumentsParsed();
                return _settingsFile;
            }
        }

        internal string? InitialCommand
        {
            get
            {
                AssertArgumentsParsed();
                return _commandLineCommand;
            }
        }

        internal bool WasInitialCommandEncoded
        {
            get
            {
                AssertArgumentsParsed();
                return _wasCommandEncoded;
            }
        }

#if !UNIX
        internal ProcessWindowStyle? WindowStyle
        {
            get
            {
                AssertArgumentsParsed();
                return _windowStyle;
            }
        }
#endif

        internal bool ShowBanner
        {
            get
            {
                AssertArgumentsParsed();
                return _showBanner;
            }
        }

        internal bool NoExit
        {
            get
            {
                AssertArgumentsParsed();
                return _noExit;
            }
        }

        internal bool SkipProfiles
        {
            get
            {
                AssertArgumentsParsed();
                return _skipUserInit;
            }
        }

        internal uint ExitCode
        {
            get
            {
                AssertArgumentsParsed();
                return _exitCode;
            }
        }

        internal bool ExplicitReadCommandsFromStdin
        {
            get
            {
                AssertArgumentsParsed();
                return _explicitReadCommandsFromStdin;
            }
        }

        internal bool NoPrompt
        {
            get
            {
                AssertArgumentsParsed();
                return _noPrompt;
            }
        }

        internal Collection<CommandParameter> Args
        {
            get
            {
                AssertArgumentsParsed();
                return _collectedArgs;
            }
        }

        internal string? ConfigurationFile
        {
            get
            {
                AssertArgumentsParsed();
                return _configurationFile;
            }
        }

        internal string? ConfigurationName
        {
            get
            {
                AssertArgumentsParsed();
                return _configurationName;
            }

            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    _configurationName = value;
                }
            }
        }

        internal bool SocketServerMode
        {
            get
            {
                AssertArgumentsParsed();
                return _socketServerMode;
            }
        }

        internal bool NamedPipeServerMode
        {
            get
            {
                AssertArgumentsParsed();
                return _namedPipeServerMode;
            }
        }

        internal bool SSHServerMode
        {
            get
            {
                AssertArgumentsParsed();
                return _sshServerMode;
            }
        }

        internal bool ServerMode
        {
            get
            {
                AssertArgumentsParsed();
                return _serverMode;
            }
        }

        // Added for using in xUnit tests
        internal string? ErrorMessage
        {
            get
            {
                AssertArgumentsParsed();
                return _error;
            }
        }

        // Added for using in xUnit tests
        internal bool ShowShortHelp
        {
            get
            {
                AssertArgumentsParsed();
                return _showHelp;
            }
        }

        // Added for using in xUnit tests
        internal bool ShowExtendedHelp
        {
            get
            {
                AssertArgumentsParsed();
                return _showExtendedHelp;
            }
        }

        internal bool NoProfileLoadTime
        {
            get
            {
                AssertArgumentsParsed();
                return _noProfileLoadTime;
            }
        }

        internal bool ShowVersion
        {
            get
            {
                AssertArgumentsParsed();
                return _showVersion;
            }
        }

        internal string? CustomPipeName
        {
            get
            {
                AssertArgumentsParsed();
                return _customPipeName;
            }
        }

        internal Serialization.DataFormat OutputFormat
        {
            get
            {
                AssertArgumentsParsed();
                return _outFormat;
            }
        }

        internal bool OutputFormatSpecified
        {
            get
            {
                AssertArgumentsParsed();
                return _outputFormatSpecified;
            }
        }

        internal Serialization.DataFormat InputFormat
        {
            get
            {
                AssertArgumentsParsed();
                return _inFormat;
            }
        }

        internal string? File
        {
            get
            {
                AssertArgumentsParsed();
                return _file;
            }
        }

        internal string? ExecutionPolicy
        {
            get
            {
                AssertArgumentsParsed();
                return _executionPolicy;
            }
        }

        internal bool StaMode
        {
            get
            {
                AssertArgumentsParsed();
                if (_staMode.HasValue)
                {
                    return _staMode.Value;
                }
                else
                {
                    return Platform.IsStaSupported;
                }
            }
        }

        internal bool ThrowOnReadAndPrompt
        {
            get
            {
                AssertArgumentsParsed();
                return _noInteractive;
            }
        }

        internal bool NonInteractive
        {
            get
            {
                AssertArgumentsParsed();
                return _noInteractive;
            }
        }

        internal string? WorkingDirectory
        {
            get
            {
                AssertArgumentsParsed();
#if !UNIX
                if (_removeWorkingDirectoryTrailingCharacter && _workingDirectory?.Length > 0)
                {
                    return _workingDirectory.Remove(_workingDirectory.Length - 1);
                }
#endif
                return _workingDirectory;
            }
        }

#if !UNIX
        internal bool RemoveWorkingDirectoryTrailingCharacter
        {
            get
            {
                AssertArgumentsParsed();
                return _removeWorkingDirectoryTrailingCharacter;
            }
        }

        internal DateTimeOffset? UTCTimestamp
        {
            get
            {
                AssertArgumentsParsed();
                return _utcTimestamp;
            }
        }

        internal string? Token
        {
            get
            {
                AssertArgumentsParsed();
                return _token;
            }
        }

        internal bool V2SocketServerMode
        {
            get
            {
                AssertArgumentsParsed();
                return _v2SocketServerMode;
            }
        }
#endif

        #endregion Internal properties

        #region static methods
        /// <summary>
        /// Processes the -SettingFile Argument.
        /// </summary>
        /// <param name="args">
        /// The command line parameters to be processed.
        /// </param>
        /// <param name="settingFileArgIndex">
        /// The index in args to the argument following '-SettingFile'.
        /// </param>
        /// <returns>
        /// Returns true if the argument was parsed successfully and false if not.
        /// </returns>
        private bool TryParseSettingFileHelper(string[] args, int settingFileArgIndex)
        {
            if (settingFileArgIndex >= args.Length)
            {
                SetCommandLineError(CommandLineParameterParserStrings.MissingSettingsFileArgument);
                return false;
            }

            string configFile;
            try
            {
                configFile = NormalizeFilePath(args[settingFileArgIndex]);
            }
            catch (Exception ex)
            {
                string error = string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidSettingsFileArgument, args[settingFileArgIndex], ex.Message);
                SetCommandLineError(error);
                return false;
            }

            if (!System.IO.File.Exists(configFile))
            {
                string error = string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.SettingsFileNotExists, configFile);
                SetCommandLineError(error);
                return false;
            }

            _settingsFile = configFile;

            return true;
        }

        internal static string GetConfigurationNameFromGroupPolicy()
        {
            // Current user policy takes precedence.
            var consoleSessionSetting = Utils.GetPolicySetting<ConsoleSessionConfiguration>(Utils.CurrentUserThenSystemWideConfig);

            return (consoleSessionSetting?.EnableConsoleSessionConfiguration == true && !string.IsNullOrEmpty(consoleSessionSetting?.ConsoleSessionConfigurationName)) ?
                    consoleSessionSetting.ConsoleSessionConfigurationName : string.Empty;
        }

        /// <summary>
        /// Gets the word in a switch from the current argument or parses a file.
        /// For example -foo, /foo, or --foo would return 'foo'.
        /// </summary>
        /// <param name="args">
        /// The command line parameters to be processed.
        /// </param>
        /// <param name="argIndex">
        /// The index in args to the argument to process.
        /// </param>
        /// <param name="noexitSeen">
        /// Used during parsing files.
        /// </param>
        /// <returns>
        /// Returns a Tuple:
        /// The first value is a String called 'switchKey' with the word in a switch from the current argument or null.
        /// The second value is a bool called 'shouldBreak', indicating if the parsing look should break.
        /// </returns>
        private (string switchKey, bool shouldBreak) GetSwitchKey(string[] args, ref int argIndex, ref bool noexitSeen)
        {
            string switchKey = args[argIndex].Trim();
            if (string.IsNullOrEmpty(switchKey))
            {
                return (switchKey: string.Empty, shouldBreak: false);
            }

            char firstChar = switchKey[0];
            if (!CharExtensions.IsDash(firstChar) && firstChar != '/')
            {
                // then it's a file
                --argIndex;
                ParseFile(args, ref argIndex, noexitSeen);

                return (switchKey: string.Empty, shouldBreak: true);
            }

            // chop off the first character so that we're agnostic wrt specifying / or -
            // in front of the switch name.
            switchKey = switchKey.Substring(1);

            // chop off the second dash so we're agnostic wrt specifying - or --
            if (!string.IsNullOrEmpty(switchKey) && CharExtensions.IsDash(firstChar) && switchKey[0] == firstChar)
            {
                switchKey = switchKey.Substring(1);
            }

            return (switchKey: switchKey, shouldBreak: false);
        }

        internal static string NormalizeFilePath(string path)
        {
            // Normalize slashes
            path = path.Replace(
                StringLiterals.AlternatePathSeparator,
                StringLiterals.DefaultPathSeparator);

            return Path.GetFullPath(path);
        }

        /// <summary>
        /// Determine the execution policy based on the supplied string.
        /// If the string doesn't match to any known execution policy, set it to incorrect.
        /// </summary>
        /// <param name="_executionPolicy">The value provided on the command line.</param>
        /// <returns>The execution policy.</returns>
        private static ParameterBitmap GetExecutionPolicy(string? _executionPolicy)
        {
            if (_executionPolicy is null)
            {
                return ParameterBitmap.EPUndefined;
            }

            ParameterBitmap executionPolicySetting = ParameterBitmap.EPIncorrect;

            if (string.Equals(_executionPolicy, "default", StringComparison.OrdinalIgnoreCase))
            {
                executionPolicySetting = ParameterBitmap.EPDefault;
            }
            else if (string.Equals(_executionPolicy, "remotesigned", StringComparison.OrdinalIgnoreCase))
            {
                executionPolicySetting = ParameterBitmap.EPRemoteSigned;
            }
            else if (string.Equals(_executionPolicy, "bypass", StringComparison.OrdinalIgnoreCase))
            {
                executionPolicySetting = ParameterBitmap.EPBypass;
            }
            else if (string.Equals(_executionPolicy, "allsigned", StringComparison.OrdinalIgnoreCase))
            {
                executionPolicySetting = ParameterBitmap.EPAllSigned;
            }
            else if (string.Equals(_executionPolicy, "restricted", StringComparison.OrdinalIgnoreCase))
            {
                executionPolicySetting = ParameterBitmap.EPRestricted;
            }
            else if (string.Equals(_executionPolicy, "unrestricted", StringComparison.OrdinalIgnoreCase))
            {
                executionPolicySetting = ParameterBitmap.EPUnrestricted;
            }
            else if (string.Equals(_executionPolicy, "undefined", StringComparison.OrdinalIgnoreCase))
            {
                executionPolicySetting = ParameterBitmap.EPUndefined;
            }

            return executionPolicySetting;
        }

        private static bool MatchSwitch(string switchKey, string match, string smallestUnambiguousMatch)
        {
            Dbg.Assert(!string.IsNullOrEmpty(match), "need a value");
            Dbg.Assert(match.Trim().ToLowerInvariant() == match, "match should be normalized to lowercase w/ no outside whitespace");
            Dbg.Assert(smallestUnambiguousMatch.Trim().ToLowerInvariant() == smallestUnambiguousMatch, "match should be normalized to lowercase w/ no outside whitespace");
            Dbg.Assert(match.Contains(smallestUnambiguousMatch), "sUM should be a substring of match");

            return (switchKey.Length >= smallestUnambiguousMatch.Length
                    && match.StartsWith(switchKey, StringComparison.OrdinalIgnoreCase));
        }

        #endregion

        private void ShowError(PSHostUserInterface hostUI)
        {
            if (_error != null)
            {
                hostUI.WriteErrorLine(_error);
            }
        }

        private void ShowHelp(PSHostUserInterface hostUI, string? helpText)
        {
            if (helpText is null)
            {
                return;
            }

            if (_showHelp)
            {
                hostUI.WriteLine();
                hostUI.Write(helpText);
                if (_showExtendedHelp)
                {
                    hostUI.Write(ManagedEntranceStrings.ExtendedHelp);
                }

                hostUI.WriteLine();
            }
        }

        private void DisplayBanner(PSHostUserInterface hostUI, string? bannerText)
        {
            if (_showBanner && !_showHelp)
            {
                // If banner text is not supplied do nothing.
                if (!string.IsNullOrEmpty(bannerText))
                {
                    hostUI.WriteLine(bannerText);
                }

                if (UpdatesNotification.CanNotifyUpdates)
                {
                    UpdatesNotification.ShowUpdateNotification(hostUI);
                }
            }
        }

        /// <summary>
        /// Processes all the command line parameters to ConsoleHost.  Returns the exit code to be used to terminate the process, or
        /// Success to indicate that the program should continue running.
        /// </summary>
        /// <param name="args">
        /// The command line parameters to be processed.
        /// </param>
        internal void Parse(string[] args)
        {
            if (_dirty)
            {
                throw new InvalidOperationException("This instance has already been used. Create a new instance.");
            }

            for (int i = 0; i < args.Length; i++)
            {
                ArgumentNullException.ThrowIfNull(args[i], CommandLineParameterParserStrings.NullElementInArgs);
            }

            // Indicates that we've called this method on this instance, and that when it's done, the state variables
            // will reflect the parse.
            _dirty = true;

            ParseHelper(args);
        }

        private void ParseHelper(string[] args)
        {
            if (args.Length == 0)
            {
                return;
            }

            bool noexitSeen = false;

            for (int i = 0; i < args.Length; ++i)
            {
                (string switchKey, bool shouldBreak) switchKeyResults = GetSwitchKey(args, ref i, ref noexitSeen);
                if (switchKeyResults.shouldBreak)
                {
                    break;
                }

                string switchKey = switchKeyResults.switchKey;

                // If version is in the commandline, don't continue to look at any other parameters
                if (MatchSwitch(switchKey, "version", "v"))
                {
                    _showVersion = true;
                    _showBanner = false;
                    _noInteractive = true;
                    _skipUserInit = true;
                    _noExit = false;
                    ParametersUsed |= ParameterBitmap.Version;
                    break;
                }

                if (MatchSwitch(switchKey, "help", "h") || MatchSwitch(switchKey, "?", "?"))
                {
                    _showHelp = true;
                    _showExtendedHelp = true;
                    _abortStartup = true;
                    ParametersUsed |= ParameterBitmap.Help;
                }
                else if (MatchSwitch(switchKey, "login", "l"))
                {
                    // On Windows, '-Login' does nothing.
                    // On *nix, '-Login' is already handled much earlier to improve startup performance, so we do nothing here.
                    ParametersUsed |= ParameterBitmap.Login;
                }
                else if (MatchSwitch(switchKey, "noexit", "noe"))
                {
                    _noExit = true;
                    noexitSeen = true;
                    ParametersUsed |= ParameterBitmap.NoExit;
                }
                else if (MatchSwitch(switchKey, "noprofile", "nop"))
                {
                    _skipUserInit = true;
                    ParametersUsed |= ParameterBitmap.NoProfile;
                }
                else if (MatchSwitch(switchKey, "nologo", "nol"))
                {
                    _showBanner = false;
                    ParametersUsed |= ParameterBitmap.NoLogo;
                }
                else if (MatchSwitch(switchKey, "noninteractive", "noni"))
                {
                    _noInteractive = true;
                    ParametersUsed |= ParameterBitmap.NonInteractive;
                }
                else if (MatchSwitch(switchKey, "socketservermode", "so"))
                {
                    _socketServerMode = true;
                    _showBanner = false;
                    ParametersUsed |= ParameterBitmap.SocketServerMode;
                }
#if !UNIX
                else if (MatchSwitch(switchKey, "v2socketservermode", "v2so"))
                {
                    _v2SocketServerMode = true;
                    _showBanner = false;
                    ParametersUsed |= ParameterBitmap.V2SocketServerMode;
                }
#endif
                else if (MatchSwitch(switchKey, "servermode", "s"))
                {
                    _serverMode = true;
                    _showBanner = false;
                    ParametersUsed |= ParameterBitmap.ServerMode;
                }
                else if (MatchSwitch(switchKey, "namedpipeservermode", "nam"))
                {
                    _namedPipeServerMode = true;
                    _showBanner = false;
                    ParametersUsed |= ParameterBitmap.NamedPipeServerMode;
                }
                else if (MatchSwitch(switchKey, "sshservermode", "sshs"))
                {
                    _sshServerMode = true;
                    _showBanner = false;
                    ParametersUsed |= ParameterBitmap.SSHServerMode;
                }
                else if (MatchSwitch(switchKey, "noprofileloadtime", "noprofileloadtime"))
                {
                    _noProfileLoadTime = true;
                    ParametersUsed |= ParameterBitmap.NoProfileLoadTime;
                }
                else if (MatchSwitch(switchKey, "interactive", "i"))
                {
                    _noInteractive = false;
                    ParametersUsed |= ParameterBitmap.Interactive;
                }
                else if (MatchSwitch(switchKey, "configurationfile", "configurationfile"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        SetCommandLineError(
                            CommandLineParameterParserStrings.MissingConfigurationFileArgument);
                        break;
                    }

                    _configurationFile = args[i];
                    ParametersUsed |= ParameterBitmap.ConfigurationFile;
                }
                else if (MatchSwitch(switchKey, "configurationname", "config"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        SetCommandLineError(
                            CommandLineParameterParserStrings.MissingConfigurationNameArgument);
                        break;
                    }

                    _configurationName = args[i];
                    ParametersUsed |= ParameterBitmap.ConfigurationName;
                }
                else if (MatchSwitch(switchKey, "custompipename", "cus"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        SetCommandLineError(
                            CommandLineParameterParserStrings.MissingCustomPipeNameArgument);
                        break;
                    }

#if UNIX
                    int maxNameLength = MaxNameLength();
                    if (args[i].Length > maxNameLength)
                    {
                        SetCommandLineError(
                            string.Format(
                                CommandLineParameterParserStrings.CustomPipeNameTooLong,
                                maxNameLength,
                                args[i],
                                args[i].Length));
                        break;
                    }
#endif

                    _customPipeName = args[i];
                    ParametersUsed |= ParameterBitmap.CustomPipeName;
                }
                else if (MatchSwitch(switchKey, "commandwithargs", "commandwithargs") || MatchSwitch(switchKey, "cwa", "cwa"))
                {
                    _commandHasArgs = true;

                    if (!ParseCommand(args, ref i, noexitSeen, false))
                    {
                        break;
                    }

                    i++;
                    CollectPSArgs(args, ref i);
                    ParametersUsed |= ParameterBitmap.CommandWithArgs;
                }
                else if (MatchSwitch(switchKey, "command", "c"))
                {
                    if (!ParseCommand(args, ref i, noexitSeen, false))
                    {
                        break;
                    }

                    ParametersUsed |= ParameterBitmap.Command;
                }
                else if (MatchSwitch(switchKey, "windowstyle", "w"))
                {
#if UNIX
                    SetCommandLineError(
                        CommandLineParameterParserStrings.WindowStyleArgumentNotImplemented);
                    break;
#else
                    ++i;
                    if (i >= args.Length)
                    {
                        SetCommandLineError(
                            CommandLineParameterParserStrings.MissingWindowStyleArgument);
                        break;
                    }

                    try
                    {
                        _windowStyle = LanguagePrimitives.ConvertTo<ProcessWindowStyle>(args[i]);
                    }
                    catch (PSInvalidCastException e)
                    {
                        SetCommandLineError(
                            string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidWindowStyleArgument, args[i], e.Message));
                        break;
                    }

                    ParametersUsed |= ParameterBitmap.WindowStyle;
#endif
                }
                else if (MatchSwitch(switchKey, "file", "f"))
                {
                    if (!ParseFile(args, ref i, noexitSeen))
                    {
                        break;
                    }

                    ParametersUsed |= ParameterBitmap.File;
                }
#if DEBUG
                else if (MatchSwitch(switchKey, "isswait", "isswait"))
                {
                    // Just toss this option, it was processed earlier in 'ManagedEntrance.Start()'.
                }
#endif
                else if (MatchSwitch(switchKey, "outputformat", "o") || MatchSwitch(switchKey, "of", "o"))
                {
                    ParseFormat(args, ref i, ref _outFormat, CommandLineParameterParserStrings.MissingOutputFormatParameter);
                    _outputFormatSpecified = true;
                    ParametersUsed |= ParameterBitmap.OutputFormat;
                }
                else if (MatchSwitch(switchKey, "inputformat", "inp") || MatchSwitch(switchKey, "if", "if"))
                {
                    ParseFormat(args, ref i, ref _inFormat, CommandLineParameterParserStrings.MissingInputFormatParameter);
                    ParametersUsed |= ParameterBitmap.InputFormat;
                }
                else if (MatchSwitch(switchKey, "executionpolicy", "ex") || MatchSwitch(switchKey, "ep", "ep"))
                {
                    ParseExecutionPolicy(args, ref i, ref _executionPolicy, CommandLineParameterParserStrings.MissingExecutionPolicyParameter);
                    ParametersUsed |= ParameterBitmap.ExecutionPolicy;
                    var executionPolicy = GetExecutionPolicy(_executionPolicy);
                    if (executionPolicy == ParameterBitmap.EPIncorrect)
                    {
                        SetCommandLineError(
                            string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidExecutionPolicyArgument, _executionPolicy),
                            showHelp: true);
                        break;
                    }

                    ParametersUsed |= executionPolicy;
                }
                else if (MatchSwitch(switchKey, "encodedcommand", "e") || MatchSwitch(switchKey, "ec", "e"))
                {
                    _wasCommandEncoded = true;
                    if (!ParseCommand(args, ref i, noexitSeen, true))
                    {
                        break;
                    }

                    ParametersUsed |= ParameterBitmap.EncodedCommand;
                }
                else if (MatchSwitch(switchKey, "encodedarguments", "encodeda") || MatchSwitch(switchKey, "ea", "ea"))
                {
                    if (!CollectArgs(args, ref i))
                    {
                        break;
                    }

                    ParametersUsed |= ParameterBitmap.EncodedArgument;
                }
                else if (MatchSwitch(switchKey, "settingsfile", "settings"))
                {
                    // Parse setting file arg and write error
                    if (!TryParseSettingFileHelper(args, ++i))
                    {
                        break;
                    }

                    ParametersUsed |= ParameterBitmap.SettingsFile;
                }
                else if (MatchSwitch(switchKey, "sta", "sta"))
                {
                    if (!Platform.IsWindowsDesktop || !Platform.IsStaSupported)
                    {
                        SetCommandLineError(
                            CommandLineParameterParserStrings.STANotImplemented);
                        break;
                    }

                    if (_staMode.HasValue)
                    {
                        // -sta and -mta are mutually exclusive.
                        SetCommandLineError(
                            CommandLineParameterParserStrings.MtaStaMutuallyExclusive);
                        break;
                    }

                    _staMode = true;
                    ParametersUsed |= ParameterBitmap.STA;
                }
                else if (MatchSwitch(switchKey, "mta", "mta"))
                {
                    if (!Platform.IsWindowsDesktop)
                    {
                        SetCommandLineError(
                            CommandLineParameterParserStrings.MTANotImplemented);
                        break;
                    }

                    if (_staMode.HasValue)
                    {
                        // -sta and -mta are mutually exclusive.
                        SetCommandLineError(
                            CommandLineParameterParserStrings.MtaStaMutuallyExclusive);
                        break;
                    }

                    _staMode = false;
                    ParametersUsed |= ParameterBitmap.MTA;
                }
                else if (MatchSwitch(switchKey, "workingdirectory", "wo") || MatchSwitch(switchKey, "wd", "wd"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        SetCommandLineError(
                            CommandLineParameterParserStrings.MissingWorkingDirectoryArgument);
                        break;
                    }

                    _workingDirectory = args[i];
                    ParametersUsed |= ParameterBitmap.WorkingDirectory;
                }
#if !UNIX
                else if (MatchSwitch(switchKey, "removeworkingdirectorytrailingcharacter", "removeworkingdirectorytrailingcharacter"))
                {
                    _removeWorkingDirectoryTrailingCharacter = true;
                }
                else if (MatchSwitch(switchKey, "token", "to"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        SetCommandLineError(
                            string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.MissingMandatoryArgument, "-Token"));
                        break;
                    }

                    _token = args[i];

                    // Not adding anything to ParametersUsed, because it is required with V2 socket server mode
                    // So, we can assume it based on that bit
                }
                else if (MatchSwitch(switchKey, "utctimestamp", "utc"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        SetCommandLineError(
                            string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.MissingMandatoryArgument, "-UTCTimestamp"));
                        break;
                    }

                    // Parse as iso8601UtcString
                    _utcTimestamp = DateTimeOffset.ParseExact(args[i], "yyyy-MM-dd'T'HH:mm:ssK", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);

                    // Not adding anything to ParametersUsed, because it is required with V2 socket server mode
                    // So, we can assume it based on that bit
                }
#endif
                else
                {
                    // The first parameter we fail to recognize marks the beginning of the file string.
                    --i;
                    if (!ParseFile(args, ref i, noexitSeen))
                    {
                        break;
                    }

                    // default to filename being the next argument.
                    ParametersUsed |= ParameterBitmap.File;
                }
            }

            Dbg.Assert(
                    ((_exitCode == ConsoleHost.ExitCodeBadCommandLineParameter) && _abortStartup)
                || (_exitCode == ConsoleHost.ExitCodeSuccess),
                "if exit code is failure, then abortstartup should be true");
        }

        internal void ShowErrorHelpBanner(PSHostUserInterface hostUI, string? bannerText, string? helpText)
        {
            ShowError(hostUI);
            ShowHelp(hostUI, helpText);
            DisplayBanner(hostUI, bannerText);
        }

        private void SetCommandLineError(string msg, bool showHelp = false, bool showBanner = false)
        {
            if (_error != null)
            {
                throw new ArgumentException(nameof(SetCommandLineError), nameof(_error));
            }

            _error = msg;
            _showHelp = showHelp;
            _showBanner = showBanner;
            _abortStartup = true;
            _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter;
        }

        private void ParseFormat(string[] args, ref int i, ref Serialization.DataFormat format, string resourceStr)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in Enum.GetNames<Serialization.DataFormat>())
            {
                sb.Append(s);
                sb.Append(Environment.NewLine);
            }

            ++i;
            if (i >= args.Length)
            {
                SetCommandLineError(
                    StringUtil.Format(
                        resourceStr,
                        sb.ToString()),
                    showHelp: true);
                return;
            }

            try
            {
                format = (Serialization.DataFormat)Enum.Parse(typeof(Serialization.DataFormat), args[i], true);
            }
            catch (ArgumentException)
            {
                SetCommandLineError(
                    StringUtil.Format(
                        CommandLineParameterParserStrings.BadFormatParameterValue,
                        args[i],
                        sb.ToString()),
                    showHelp: true);
            }
        }

        private void ParseExecutionPolicy(string[] args, ref int i, ref string? executionPolicy, string resourceStr)
        {
            ++i;
            if (i >= args.Length)
            {
                SetCommandLineError(resourceStr, showHelp: true);
                return;
            }

            executionPolicy = args[i];
        }

        // Process file execution. We don't need to worry about checking -command
        // since if -command comes before -file, -file will be treated as part
        // of the script to evaluate. If -file comes before -command, it will
        // treat -command as an argument to the script...
        private bool ParseFile(string[] args, ref int i, bool noexitSeen)
        {
            ++i;
            if (i >= args.Length)
            {
                SetCommandLineError(
                    CommandLineParameterParserStrings.MissingFileArgument,
                    showHelp: true,
                    showBanner: false);
                return false;
            }

            // Don't show the startup banner unless -noexit has been specified.
            if (!noexitSeen)
                _showBanner = false;

            // Process interactive input...
            if (args[i] == "-")
            {
                // the arg to -file is -, which is secret code for "read the commands from stdin with prompts"

                _explicitReadCommandsFromStdin = true;
                _noPrompt = false;
            }
            else
            {
                // Exit on script completion unless -noexit was specified...
                if (!noexitSeen)
                    _noExit = false;

                // We need to get the full path to the script because it will be
                // executed after the profiles are run and they may change the current
                // directory.
                try
                {
                    _file = NormalizeFilePath(args[i]);
                }
                catch (Exception e)
                {
                    // Catch all exceptions - we're just going to exit anyway so there's
                    // no issue of the system being destabilized.
                    SetCommandLineError(
                        string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidFileArgument, args[i], e.Message),
                        showBanner: false);
                    return false;
                }

                if (!System.IO.File.Exists(_file))
                {
                    if (args[i].StartsWith('-') && args[i].Length > 1)
                    {
                        string param = args[i].Substring(1, args[i].Length - 1);
                        StringBuilder possibleParameters = new StringBuilder();
                        foreach (string validParameter in s_validParameters)
                        {
                            if (validParameter.Contains(param, StringComparison.OrdinalIgnoreCase))
                            {
                                possibleParameters.Append("\n  -");
                                possibleParameters.Append(validParameter);
                            }
                        }

                        if (possibleParameters.Length > 0)
                        {
                            SetCommandLineError(
                                string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidArgument, args[i])
                                    + Environment.NewLine
                                    + possibleParameters.ToString(),
                                showBanner: false);
                            return false;
                        }
                    }

                    SetCommandLineError(
                        string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.ArgumentFileDoesNotExist, args[i]),
                        showHelp: true);
                    return false;
                }
#if !UNIX
                // Only do the .ps1 extension check on Windows since shebang is not supported
                if (!_file.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
                {
                    SetCommandLineError(string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidFileArgumentExtension, args[i]));
                    return false;
                }
#endif

                i++;

                CollectPSArgs(args, ref i);
            }

            return true;
        }

        private void CollectPSArgs(string[] args, ref int i)
        {
            // Try parse '$true', 'true', '$false' and 'false' values.
            static object ConvertToBoolIfPossible(string arg)
            {
                // Before parsing we skip '$' if present.
                return arg.Length > 0 && bool.TryParse(arg.AsSpan(arg[0] == '$' ? 1 : 0), out bool boolValue)
                    ? (object)boolValue
                    : (object)arg;
            }

            string? pendingParameter = null;

            while (i < args.Length)
            {
                string arg = args[i];

                // If there was a pending parameter, add a named parameter
                // using the pending parameter and current argument
                if (pendingParameter != null)
                {
                    _collectedArgs.Add(new CommandParameter(pendingParameter, arg));
                    pendingParameter = null;
                }
                else if (!string.IsNullOrEmpty(arg) && CharExtensions.IsDash(arg[0]) && arg.Length > 1)
                {
                    int offset = arg.IndexOf(':');
                    if (offset >= 0)
                    {
                        if (offset == arg.Length - 1)
                        {
                            pendingParameter = arg.TrimEnd(':');
                        }
                        else
                        {
                            string argValue = arg.Substring(offset + 1);
                            string argName = arg.Substring(0, offset);
                            _collectedArgs.Add(new CommandParameter(argName, ConvertToBoolIfPossible(argValue)));
                        }
                    }
                    else
                    {
                        _collectedArgs.Add(new CommandParameter(arg));
                    }
                }
                else
                {
                    _collectedArgs.Add(new CommandParameter(null, arg));
                }

                ++i;
            }
        }

        private bool ParseCommand(string[] args, ref int i, bool noexitSeen, bool isEncoded)
        {
            if (_commandLineCommand != null)
            {
                // we've already set the command, so squawk
                SetCommandLineError(CommandLineParameterParserStrings.CommandAlreadySpecified, showHelp: true);
                return false;
            }

            ++i;
            if (i >= args.Length)
            {
                SetCommandLineError(CommandLineParameterParserStrings.MissingCommandParameter, showHelp: true);
                return false;
            }

            if (isEncoded)
            {
                try
                {
                    _commandLineCommand = StringToBase64Converter.Base64ToString(args[i]);
                }
                // decoding failed
                catch
                {
                    SetCommandLineError(CommandLineParameterParserStrings.BadCommandValue, showHelp: true);
                    return false;
                }
            }
            else if (args[i] == "-")
            {
                // the arg to -command is -, which is secret code for "read the commands from stdin with no prompts"

                _explicitReadCommandsFromStdin = true;
                _noPrompt = true;

                ++i;
                if (i != args.Length)
                {
                    // there are more parameters to -command than -, which is an error.

                    SetCommandLineError(CommandLineParameterParserStrings.TooManyParametersToCommand, showHelp: true);
                    return false;
                }

                if (InputRedirectedTestHook.HasValue ? !InputRedirectedTestHook.Value : !Console.IsInputRedirected)
                {
                    SetCommandLineError(CommandLineParameterParserStrings.StdinNotRedirected, showHelp: true);
                    return false;
                }
            }
            else
            {
                if (_commandHasArgs)
                {
                    _commandLineCommand = args[i];
                }
                else
                {
                    _commandLineCommand = string.Join(' ', args, i, args.Length - i);
                    i = args.Length;
                }
            }

            if (!noexitSeen && !_explicitReadCommandsFromStdin)
            {
                // don't reset this if they've already specified -noexit
                _noExit = false;
            }

            _showBanner = false;

            return true;
        }

        private bool CollectArgs(string[] args, ref int i)
        {
            if (_collectedArgs.Count != 0)
            {
                SetCommandLineError(CommandLineParameterParserStrings.ArgsAlreadySpecified, showHelp: true);
                return false;
            }

            ++i;
            if (i >= args.Length)
            {
                SetCommandLineError(CommandLineParameterParserStrings.MissingArgsValue, showHelp: true);
                return false;
            }

            try
            {
                object[] a = StringToBase64Converter.Base64ToArgsConverter(args[i]);
                if (a != null)
                {
                    foreach (object obj in a)
                    {
                        _collectedArgs.Add(new CommandParameter(null, obj));
                    }
                }
            }
            catch
            {
                // decoding failed
                SetCommandLineError(CommandLineParameterParserStrings.BadArgsValue, showHelp: true);
                return false;
            }

            return true;
        }

        private bool _socketServerMode;
#if !UNIX
        private bool _v2SocketServerMode;
#endif
        private bool _serverMode;
        private bool _namedPipeServerMode;
        private bool _sshServerMode;
        private bool _noProfileLoadTime;
        private bool _showVersion;
        private string? _configurationFile;
        private string? _configurationName;
        private string? _error;
        private bool _showHelp;
        private bool _showExtendedHelp;
        private bool _showBanner = true;
        private bool _noInteractive;
        private bool _abortStartup;
        private bool _skipUserInit;
        private string? _customPipeName;
        private bool? _staMode = null;
        private bool _noExit = true;
        private bool _explicitReadCommandsFromStdin;
        private bool _noPrompt;
        private string? _commandLineCommand;
        private bool _wasCommandEncoded;
        private bool _commandHasArgs;
        private uint _exitCode = ConsoleHost.ExitCodeSuccess;
        private bool _dirty;
        private Serialization.DataFormat _outFormat = Serialization.DataFormat.Text;
        private bool _outputFormatSpecified = false;
        private Serialization.DataFormat _inFormat = Serialization.DataFormat.Text;
        private readonly Collection<CommandParameter> _collectedArgs = new Collection<CommandParameter>();
        private string? _file;
        private string? _executionPolicy;
        private string? _settingsFile;
        private string? _workingDirectory;
#if !UNIX
        private string? _token;
        private DateTimeOffset? _utcTimestamp;
#endif

#if !UNIX
        private ProcessWindowStyle? _windowStyle;
        private bool _removeWorkingDirectoryTrailingCharacter = false;
#endif
    }
}   // namespace