How to ignore unrecognized command line parameters

816 views Asked by At

I'm testing out System.CommandLine.

There will be several options passed to my executable, but I only care about one of them. If I don't define them all, I will get errors:

Unrecognized command or argument '-i'.
Unrecognized command or argument '3'.

Is there any way that I can tell System.CommandLine to ignore any options that aren't specified by my code? E.g.:

var root = New RootCommand("Test application");
var cmd = new Command("--example", "example command");
root.Add(cmd);
await root.InvokeAsync(args);

Then if I try calling my program via:

test example --startDir=C:\temp --FileCnt=7 --Delay=10

I'll get 6 of those 'Unrecognized command or argument' errors.

The reason that I would like to not have to specify all the options is that my program is called from another program. The parameters are being passed from the calling program, and I don't know what all of them will be.

I do know what the two important ones I need to parse are, and the rest I don't care about.

2

There are 2 answers

0
YukiShu On

I recently run into similar problems. For my workaround, I try to call parse first then invoke. Like this:

var processedRes = Commands.RootCommand.Parse(args);
await processedRes.InvokeAsync();

This will ignore all unknown tokens.

0
stefan On

The command type has a property TreatUnmatchedTokensAsErrors that you can set to false.

command.TreatUnmatchedTokensAsErrors = false;

more info in the docs