-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
CommandLineParameterParser.cs
1407 lines (1245 loc) · 48.2 KB
/
CommandLineParameterParser.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.IO;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Configuration;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Internal;
using System.Diagnostics;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Host;
using System.Collections.Generic;
using System.Security;
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
{
get { return 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
{
internal static string[] validParameters = {
"version",
"nologo",
"noexit",
#if STAMODE
"sta",
"mta",
#endif
"noprofile",
"noninteractive",
"inputformat",
"outputformat",
"windowstyle",
"encodedcommand",
"configurationname",
"file",
"executionpolicy",
"command",
"settingsfile",
"help",
"workingdirectory",
"removeworkingdirectorytrailingcharacter"
};
internal CommandLineParameterParser(PSHostUserInterface hostUI, string bannerText, string helpText)
{
if (hostUI == null) { throw new PSArgumentNullException("hostUI"); }
_hostUI = hostUI;
_bannerText = bannerText;
_helpText = helpText;
}
#region Internal properties
internal bool AbortStartup
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _abortStartup;
}
}
internal string InitialCommand
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _commandLineCommand;
}
}
internal bool WasInitialCommandEncoded
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _wasCommandEncoded;
}
}
internal bool ShowBanner
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _showBanner;
}
}
internal bool NoExit
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _noExit;
}
}
internal bool SkipProfiles
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _skipUserInit;
}
}
internal uint ExitCode
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _exitCode;
}
}
internal bool ExplicitReadCommandsFromStdin
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _explicitReadCommandsFromStdin;
}
}
internal bool NoPrompt
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _noPrompt;
}
}
internal Collection<CommandParameter> Args
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _collectedArgs;
}
}
internal string ConfigurationName
{
get { return _configurationName; }
}
internal bool SocketServerMode
{
get
{
return _socketServerMode;
}
}
internal bool NamedPipeServerMode
{
get { return _namedPipeServerMode; }
}
internal bool SSHServerMode
{
get { return _sshServerMode; }
}
internal bool ServerMode
{
get
{
return _serverMode;
}
}
internal bool ShowVersion
{
get
{
return _showVersion;
}
}
internal Serialization.DataFormat OutputFormat
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _outFormat;
}
}
internal bool OutputFormatSpecified
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _outputFormatSpecified;
}
}
internal Serialization.DataFormat InputFormat
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _inFormat;
}
}
internal string File
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _file;
}
}
internal string ExecutionPolicy
{
get
{
Dbg.Assert(_dirty, "Parse has not been called yet");
return _executionPolicy;
}
}
internal bool ThrowOnReadAndPrompt
{
get
{
return _noInteractive;
}
}
internal bool NonInteractive
{
get { return _noInteractive; }
}
internal string WorkingDirectory
{
get
{
#if !UNIX
if (_removeWorkingDirectoryTrailingCharacter && _workingDirectory.Length > 0)
{
return _workingDirectory.Remove(_workingDirectory.Length - 1);
}
#endif
return _workingDirectory;
}
}
#if !UNIX
internal bool RemoveWorkingDirectoryTrailingCharacter
{
get { return _removeWorkingDirectoryTrailingCharacter; }
}
#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>
/// <param name="parser">
/// Used to allow the helper to write errors to the console. If not supplied, no errors will be written.
/// </param>
/// <returns>
/// Returns true if the argument was parsed successfully and false if not.
/// </returns>
private static bool TryParseSettingFileHelper(string[] args, int settingFileArgIndex, CommandLineParameterParser parser)
{
if (settingFileArgIndex >= args.Length)
{
if (parser != null)
{
parser.WriteCommandLineError(
CommandLineParameterParserStrings.MissingSettingsFileArgument);
}
return false;
}
string configFile = null;
try
{
configFile = NormalizeFilePath(args[settingFileArgIndex]);
}
catch (Exception ex)
{
if (parser != null)
{
string error = string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidSettingsFileArgument, args[settingFileArgIndex], ex.Message);
parser.WriteCommandLineError(error);
}
return false;
}
if (!System.IO.File.Exists(configFile))
{
if (parser != null)
{
string error = string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.SettingsFileNotExists, configFile);
parser.WriteCommandLineError(error);
}
return false;
}
PowerShellConfig.Instance.SetSystemConfigFilePath(configFile);
return true;
}
/// <summary>
/// Processes the command line parameters to ConsoleHost which must be parsed before the Host is created.
/// Success to indicate that the program should continue running.
/// </summary>
/// <param name="args">
/// The command line parameters to be processed.
/// </param>
internal static void EarlyParse(string[] args)
{
// indicates that we've called this method on this instance, and that when it's done, the state variables
// will reflect the parse.
EarlyParseHelper(args);
}
private 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>
/// Processes the command line parameters to ConsoleHost which must be parsed before the Host is created.
/// Success to indicate that the program should continue running.
/// </summary>
/// <param name="args">
/// The command line parameters to be processed.
/// </param>
private static void EarlyParseHelper(string[] args)
{
if(args == null)
{
Dbg.Assert(args != null, "Argument 'args' to EarlyParseHelper should never be null");
return;
}
bool noexitSeen = false;
for (int i = 0; i < args.Length; ++i)
{
(string SwitchKey, bool ShouldBreak) switchKeyResults = GetSwitchKey(args, ref i, parser: null, ref noexitSeen);
if (switchKeyResults.ShouldBreak)
{
break;
}
string switchKey = switchKeyResults.SwitchKey;
if (MatchSwitch(switchKey, match: "settingsfile", smallestUnambiguousMatch: "settings"))
{
// parse setting file arg and don't write error as there is no host yet.
if (!TryParseSettingFileHelper(args, ++i, parser: null))
{
break;
}
}
}
}
/// <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="parser">
/// Used to parse files in the args. If not supplied, Files will not be parsed.
/// </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 static (string SwitchKey, bool ShouldBreak) GetSwitchKey(string[] args, ref int argIndex, CommandLineParameterParser parser, ref bool noexitSeen)
{
string switchKey = args[argIndex].Trim().ToLowerInvariant();
if (string.IsNullOrEmpty(switchKey))
{
return (SwitchKey: null, ShouldBreak: false);
}
if (!SpecialCharacters.IsDash(switchKey[0]) && switchKey[0] != '/')
{
// then its a file
if (parser != null)
{
--argIndex;
parser.ParseFile(args, ref argIndex, noexitSeen);
}
return (SwitchKey: null, 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) && SpecialCharacters.IsDash(switchKey[0]))
{
switchKey = switchKey.Substring(1);
}
return (SwitchKey: switchKey, ShouldBreak: false);
}
private static string NormalizeFilePath(string path)
{
// Normalize slashes
path = path.Replace(StringLiterals.AlternatePathSeparator,
StringLiterals.DefaultPathSeparator);
return Path.GetFullPath(path);
}
private static bool MatchSwitch(string switchKey, string match, string smallestUnambiguousMatch)
{
Dbg.Assert(switchKey != null, "need a value");
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 (match.Trim().ToLowerInvariant().IndexOf(switchKey, StringComparison.Ordinal) == 0 &&
switchKey.Length >= smallestUnambiguousMatch.Length);
}
#endregion
private void ShowHelp()
{
Dbg.Assert(_helpText != null, "_helpText should not be null");
_hostUI.WriteLine(string.Empty);
_hostUI.Write(_helpText);
if (_showExtendedHelp)
{
_hostUI.Write(ManagedEntranceStrings.ExtendedHelp);
}
_hostUI.WriteLine(string.Empty);
}
private void DisplayBanner()
{
// If banner text is not supplied do nothing.
if (!string.IsNullOrEmpty(_bannerText))
{
_hostUI.WriteLine(_bannerText);
_hostUI.WriteLine();
}
}
#if STAMODE
internal bool StaMode
{
get
{
if (_staMode.HasValue)
{
return _staMode.Value;
}
else
{
// Nano doesn't support STA COM apartment, so on Nano powershell has to use MTA as the default.
// return false;
// Win8: 182409 PowerShell 3.0 should run in STA mode by default
return true;
}
}
}
#endif
/// <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)
{
Dbg.Assert(!_dirty, "This instance has already been used. Create a new instance.");
// 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);
// Check registry setting for a Group Policy ConfigurationName entry and
// use it to override anything set by the user.
var configurationName = GetConfigurationNameFromGroupPolicy();
if (!string.IsNullOrEmpty(configurationName))
{
_configurationName = configurationName;
}
}
private void ParseHelper(string[] args)
{
Dbg.Assert(args != null, "Argument 'args' to ParseHelper should never be null");
bool noexitSeen = false;
for (int i = 0; i < args.Length; ++i)
{
(string SwitchKey, bool ShouldBreak) switchKeyResults = GetSwitchKey(args, ref i, this, 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;
break;
}
else if (MatchSwitch(switchKey, "help", "h") || MatchSwitch(switchKey, "?", "?"))
{
_showHelp = true;
_showExtendedHelp = true;
_abortStartup = true;
}
else if (MatchSwitch(switchKey, "noexit", "noe"))
{
_noExit = true;
noexitSeen = true;
}
else if (MatchSwitch(switchKey, "noprofile", "nop"))
{
_skipUserInit = true;
}
else if (MatchSwitch(switchKey, "nologo", "nol"))
{
_showBanner = false;
}
else if (MatchSwitch(switchKey, "noninteractive", "noni"))
{
_noInteractive = true;
}
else if (MatchSwitch(switchKey, "socketservermode", "so"))
{
_socketServerMode = true;
}
else if (MatchSwitch(switchKey, "servermode", "s"))
{
_serverMode = true;
}
else if (MatchSwitch(switchKey, "namedpipeservermode", "nam"))
{
_namedPipeServerMode = true;
}
else if (MatchSwitch(switchKey, "sshservermode", "sshs"))
{
_sshServerMode = true;
}
else if (MatchSwitch(switchKey, "interactive", "i"))
{
_noInteractive = false;
}
else if (MatchSwitch(switchKey, "configurationname", "config"))
{
++i;
if (i >= args.Length)
{
WriteCommandLineError(
CommandLineParameterParserStrings.MissingConfigurationNameArgument);
break;
}
_configurationName = args[i];
}
else if (MatchSwitch(switchKey, "command", "c"))
{
if (!ParseCommand(args, ref i, noexitSeen, false))
{
break;
}
}
else if (MatchSwitch(switchKey, "windowstyle", "w"))
{
#if UNIX
WriteCommandLineError(
CommandLineParameterParserStrings.WindowStyleArgumentNotImplemented);
break;
#else
++i;
if (i >= args.Length)
{
WriteCommandLineError(
CommandLineParameterParserStrings.MissingWindowStyleArgument);
break;
}
try
{
ProcessWindowStyle style = (ProcessWindowStyle)LanguagePrimitives.ConvertTo(
args[i], typeof(ProcessWindowStyle), CultureInfo.InvariantCulture);
ConsoleControl.SetConsoleMode(style);
}
catch (PSInvalidCastException e)
{
WriteCommandLineError(
string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidWindowStyleArgument, args[i], e.Message));
break;
}
#endif
}
else if (MatchSwitch(switchKey, "file", "f"))
{
if (!ParseFile(args, ref i, noexitSeen))
{
break;
}
}
#if DEBUG
// this option is useful when debugging ConsoleHost remotely using VS remote debugging, as you can only
// attach to an already running process with that debugger.
else if (MatchSwitch(switchKey, "wait", "w"))
{
// This does not need to be localized: its chk only
((ConsoleHostUserInterface)_hostUI).WriteToConsole("Waiting - type enter to continue:", false);
_hostUI.ReadLine();
}
// this option is useful for testing the initial InitialSessionState experience
else if (MatchSwitch(switchKey, "iss", "iss"))
{
// Just toss this option, it was processed earlier...
}
// this option is useful for testing the initial InitialSessionState experience
// this is independent of the normal wait switch because configuration processing
// happens so early in the cycle...
else if (MatchSwitch(switchKey, "isswait", "isswait"))
{
// Just toss this option, it was processed earlier...
}
else if (MatchSwitch(switchKey, "modules", "mod"))
{
if (ConsoleHost.DefaultInitialSessionState == null)
{
WriteCommandLineError(
"The -module option can only be specified with the -iss option.",
showHelp: true,
showBanner: false);
break;
}
++i;
int moduleCount = 0;
// Accumulate the arguments to this script...
while (i < args.Length)
{
string arg = args[i];
if (!string.IsNullOrEmpty(arg) && SpecialCharacters.IsDash(arg[0]))
{
break;
}
else
{
ConsoleHost.DefaultInitialSessionState.ImportPSModule(new string[] { arg });
moduleCount++;
}
++i;
}
if (moduleCount < 1)
{
_hostUI.WriteErrorLine("No modules specified for -module option");
}
}
#endif
else if (MatchSwitch(switchKey, "outputformat", "o") || MatchSwitch(switchKey, "of", "o"))
{
ParseFormat(args, ref i, ref _outFormat, CommandLineParameterParserStrings.MissingOutputFormatParameter);
_outputFormatSpecified = true;
}
else if (MatchSwitch(switchKey, "inputformat", "in") || MatchSwitch(switchKey, "if", "if"))
{
ParseFormat(args, ref i, ref _inFormat, CommandLineParameterParserStrings.MissingInputFormatParameter);
}
else if (MatchSwitch(switchKey, "executionpolicy", "ex") || MatchSwitch(switchKey, "ep", "ep"))
{
ParseExecutionPolicy(args, ref i, ref _executionPolicy, CommandLineParameterParserStrings.MissingExecutionPolicyParameter);
}
else if (MatchSwitch(switchKey, "encodedcommand", "e") || MatchSwitch(switchKey, "ec", "e"))
{
_wasCommandEncoded = true;
if (!ParseCommand(args, ref i, noexitSeen, true))
{
break;
}
}
else if (MatchSwitch(switchKey, "encodedarguments", "encodeda") || MatchSwitch(switchKey, "ea", "ea"))
{
if (!CollectArgs(args, ref i))
{
break;
}
}
else if (MatchSwitch(switchKey, "settingsfile", "settings"))
{
// Parse setting file arg and write error
if (!TryParseSettingFileHelper(args, ++i, this))
{
break;
}
}
#if STAMODE
// explicit setting of the ApartmentState Not supported on NanoServer
else if (MatchSwitch(switchKey, "sta", "s"))
{
if (_staMode.HasValue)
{
// -sta and -mta are mutually exclusive.
WriteCommandLineError(
CommandLineParameterParserStrings.MtaStaMutuallyExclusive);
break;
}
_staMode = true;
}
// Win8: 182409 PowerShell 3.0 should run in STA mode by default..so, consequently adding the switch -mta.
// Not deleting -sta for backward compatability reasons
else if (MatchSwitch(switchKey, "mta", "mta"))
{
if (_staMode.HasValue)
{
// -sta and -mta are mutually exclusive.
WriteCommandLineError(
CommandLineParameterParserStrings.MtaStaMutuallyExclusive);
break;
}
_staMode = false;
}
#endif
else if (MatchSwitch(switchKey, "workingdirectory", "wo") || MatchSwitch(switchKey, "wd", "wd"))
{
++i;
if (i >= args.Length)
{
WriteCommandLineError(
CommandLineParameterParserStrings.MissingWorkingDirectoryArgument);
break;
}
_workingDirectory = args[i];
}
#if !UNIX
else if (MatchSwitch(switchKey, "removeworkingdirectorytrailingcharacter", "removeworkingdirectorytrailingcharacter"))
{
_removeWorkingDirectoryTrailingCharacter = true;
}
#endif
else
{
// The first parameter we fail to recognize marks the beginning of the file string.
--i;
if (!ParseFile(args, ref i, noexitSeen))
{
break;
}
}
}
if (_showHelp)
{
ShowHelp();
}
if (_showBanner && !_showHelp)
{
DisplayBanner();
}
Dbg.Assert(
((_exitCode == ConsoleHost.ExitCodeBadCommandLineParameter) && _abortStartup)
|| (_exitCode == ConsoleHost.ExitCodeSuccess),
"if exit code is failure, then abortstartup should be true");
}
private void WriteCommandLineError(string msg, bool showHelp = false, bool showBanner = false)
{
_hostUI.WriteErrorLine(msg);
_showHelp = showHelp;
_showBanner = showBanner;
_abortStartup = true;
_exitCode = ConsoleHost.ExitCodeBadCommandLineParameter;
}