蛋糕脚本本质上只是一个常规的.NET进程,您可以通过System.Environment.GetCommandLineArgs()
访问它。
示例PoC
下面是一种使用Mono.Options和Cake的快速而简单的示例方法:
#addin nuget:?package=Mono.Options&version=5.3.0.1
using Mono.Options;
public static class MyOptions
{
public static bool ShouldShowHelp { get; set; } = false;
public static List<string> Names { get; set; } = new List<string>();
public static int Repeat { get; set; } = 1;
}
var p = new OptionSet {
{ "name=", "the name of someone to greet.", n => MyOptions.Names.Add (n) },
{ "repeat=", "the number of times to MyOptions.Repeat the greeting.", (int r) => MyOptions.Repeat = r },
{ "options", "show this message and exit", h => MyOptions.ShouldShowHelp = h != null },
};
try {
p.Parse (
System.Environment.GetCommandLineArgs()
.SkipWhile(arg=>arg.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)||arg.EndsWith(".cake", StringComparison.OrdinalIgnoreCase))
.ToArray()
);
}
catch (OptionException e) {
Information("Options Sample: ");
Information (e.Message);
Information ("--options' for more information.");
return;
}
if (MyOptions.ShouldShowHelp || MyOptions.Names.Count == 0)
{
var sw = new StringWriter();
p.WriteOptionDescriptions (sw);
Information(
"Usage: [OPTIONS]"
);
Information(sw);
return;
}
string message = "Hello {0}!";
foreach (string name in MyOptions.Names) {
for (int i = 0; i < MyOptions.Repeat; ++i)
Information (message, name);
}
示例输出
未指定名称时,cake .\Mono.Options.cake
将输出帮助信息。
![没有参数](https://istack.dev59.com/VvVvz.webp)
cake .\Mono.Options.cake --options
将输出 "help"。
![已指定名称](https://istack.dev59.com/F3VtF.webp)
cake .\Mono.Options.cake --name=Mattias
将向我问候。
![已指定名称](https://istack.dev59.com/9u5Vx.webp)
cake .\Mono.Options.cake --name="Mattias" --repeat=5
将向我问候5次。
![已指定名称和重复次数](https://istack.dev59.com/NtPU8.webp)
cake .\Mono.Options.cake --name="Mattias" --repeat=sdss
将由于重复次数不是数字而失败并报告错误。
![输入图像说明](https://istack.dev59.com/Cgckj.webp)