### Output for three actions Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Example output for the {{each action in Actions}} template when the program has three actions defined. ```text action1 - action 1 description here action2 - action 2 description here action3 - action 3 description here ``` -------------------------------- ### Example command line for SuperEncoder Source: https://github.com/adamabdelhamed/powerargs/wiki/Action-Framework Shows a sample command line that a user would run to invoke the 'encode' action with a source file, output file, and encoder option. ```text SuperEncoder encode fromFile toFile -encoder Wmv ``` -------------------------------- ### Enumerate collection with {{each action in Actions}} Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Enumerates over a collection to include multiple template fragments. For each action, outputs its DefaultAlias and Description. The example output shows three actions. ```text {{each action in Actions}} {{action.DefaultAlias!}} - {{action.Description!}} !{{each}} ``` -------------------------------- ### Implement ITabCompletionSource for file-based completions Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Implements ITabCompletionSource to load completions from a text file. The TryComplete method returns a single matching word if exactly one word starts with the current input, otherwise returns false. ```csharp public class TextFileTabCompletionSource : ITabCompletionSource { string[] words; public TextFileTabCompletionSource(string file) { words = File.ReadAllLines(file); } public bool TryComplete(bool shift, string soFar, out string completion) { var match = from w in words where w.StartsWith(soFar) select w; if (match.Count() == 1) { completion = match.Single(); return true; } else { completion = null; return false; } } } ``` -------------------------------- ### Generate usage string with ArgUsage.GetUsage() Source: https://github.com/adamabdelhamed/powerargs/wiki/Autogenerated-Usage Call ArgUsage.GetUsage() with the argument type to generate a usage string. The output is a formatted help text that includes the program name, example command, global options, and action-specific options. ```csharp string usage = ArgUsage.GetUsage(); ``` -------------------------------- ### VideoEncoderArgs class with action methods and example attribute Source: https://github.com/adamabdelhamed/powerargs/wiki/Action-Framework Defines the main argument class for a video encoder console app. It includes an 'Action' property marked with [ArgRequired] and [ArgPosition(0)], action-specific properties (EncodeArgs, ClipArgs), and static methods 'Encode' and 'Clip' that receive the parsed action arguments. The [ArgExample] attribute shows a sample command line. ```csharp [ArgExample("superencoder encode fromFile toFile -encoder Wmv", "Encode the file at 'fromFile' to an AVI at 'toFile'")] public class VideoEncoderArgs { [ArgRequired] [ArgPosition(0)] public string Action { get; set; } public EncodeArgs EncodeArgs { get; set; } public ClipArgs ClipArgs { get; set; } public bool WhatIf { get; set; } public static void Encode(EncodeArgs args) { // Code to perform action here - parsed args passed in for you } public static void Clip(ClipArgs args) { // Code to perform action here - parsed args passed in for you } } ``` -------------------------------- ### Enable tab completion with [TabCompletion] Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Enables tab completion for command line arguments. When users run the program with no arguments, they get an enhanced prompt (should turn blue) with tab completion for argument names. ```csharp [TabCompletion] public class TestArgs { [ArgRequired] public string SomeParam { get; set; } public int AnotherParam { get; set; } } ``` -------------------------------- ### Get ambient arguments with Args.GetAmbientArgs Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Retrieves the most recent parsed instance of MyArgs on the current thread, allowing access to global options without passing the result through your code. ```csharp MyArgs parsed = Args.GetAmbientArgs(); ``` -------------------------------- ### Parse command-line arguments with PowerArgs Source: https://github.com/adamabdelhamed/powerargs/wiki/Home Basic PowerArgs example: defines a class with a StringArg property and parses command-line arguments into it using Args.Parse. The program accepts an optional '-StringArg' or '-s' argument and prints the entered value. ```csharp public class MyArgs { public string StringArg { get; set; } } class Program { static void Main(string[] args) { var parsed = Args.Parse(args); Console.WriteLine("You entered StringArg '{0}'", parsed.StringArg); } } ``` -------------------------------- ### Specify tab completion indicator with [TabCompletion("$")] Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Specifies an indicator string "$" for tab completion. Only users who specify the indicator as the only argument will get the enhanced prompt. ```csharp [TabCompletion("$")] public class TestArgs { [ArgRequired] public string SomeParam { get; set; } public int AnotherParam { get; set; } } ``` -------------------------------- ### Sample usage output for VideoEncoderArgs Source: https://github.com/adamabdelhamed/powerargs/wiki/Autogenerated-Usage Sample output from GetUsage() showing the generated usage text. It lists the global -whatif option and the Encode and Clip actions with their options, types, order, and descriptions. ```text Usage: superencoder options EXAMPLE: superencoder encode fromFile toFile -encoder Wmv Encode the file at 'fromFile' to an AVI at 'toFile' Global options: OPTION TYPE ORDER DESCRIPTION -whatif (-w) Switch Simulate the encoding operation Actions: Encode - Encode a new video file OPTION TYPE ORDER DESCRIPTION -source (-s) String* 1 The source video file -output (-o) String 2 Output file. If not specfied, defaults to current directory -encoder (-e) Encoder The type of encoder to use Clip - Save a portion of a video to a new video file OPTION TYPE ORDER DESCRIPTION -source (-s) String* 1 The source video file -output (-o) String 2 Output file. If not specfied, defaults to current directory -from (-f) Double The starting point of the video, in seconds -to (-t) Double The ending point of the video, in seconds -encoder (-e) Encoder The type of encoder to use ``` -------------------------------- ### Run template benchmarks Source: https://github.com/adamabdelhamed/powerargs/blob/master/AGENTS.md Runs the template benchmarks in the PowerArgs.Benchmarks project. Add --profile to collect EventPipe CPU traces. ```bash dotnet run -c Release --project PowerArgs.Benchmarks -- --template-only ``` -------------------------------- ### Basic placeholder replacement with {{ExeName !}} Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Shows the basic placeholder syntax for inserting a property value into a template. The {{ExeName !}} tag is replaced with the program name, e.g., 'myprogram'. ```text {{ExeName !}} is the best // outputs - 'myprogram is the best' ``` -------------------------------- ### Render template with DocumentRenderer Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Shows how to use the general-purpose DocumentRenderer to bind any string template to a plain .NET object. Dynamic objects are not supported. The output is 'Hi Adam'. ```cs var renderer = new DocumentRenderer(); var document = renderer.Render("Hi {{ Name !}}", new { Name = "Adam" }); // outputs 'Hi Adam' ``` -------------------------------- ### Placeholder with color parameter {{ExeName Cyan !}} Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Adds a ConsoleColor parameter to the replacement tag to specify the color when printed as a ConsoleString. Any ConsoleColor value can be used as the parameter. ```text {{ExeName Cyan !}} ``` -------------------------------- ### Define positional arguments with ArgPosition Source: https://github.com/adamabdelhamed/powerargs/wiki/Positional-Args Defines a class with two positional arguments using ArgPosition attributes, then shows how to invoke the tool with positional values. The first positional argument (index 0) is the configuration name, and the second (index 1) is the value. ```csharp public class ConfigArgs { [ArgPosition(0)] [ArgDescription("The name of the configuration element to update")] public string ConfigName { get; set; } [ArgPosition(1)] [ArgDescription("The value of the configuration element to update")] public string ConfigValue { get; set; } } ``` ```shell > mytool SomeConfigKey SomeConfigValue ``` -------------------------------- ### Parse command line arguments with PowerArgs Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Shows the basic parsing workflow: define a class with attributes like [ArgRequired(PromptIfMissing=true)] and [ArgRange(0,60)], then call Args.Parse(args). The required string argument prompts if missing; the int argument must be between 0 and 60. Catch ArgException to display the error message and auto-generated usage via ArgUsage.GenerateUsageFromTemplate(). ```csharp // A class that describes the command line arguments for this program public class MyArgs { // This argument is required and if not specified the user will // be prompted. [ArgRequired(PromptIfMissing=true)] public string StringArg { get; set; } // This argument is not required, but if specified must be >= 0 and <= 60 [ArgRange(0,60)] public int IntArg { get; set; } } class Program { static void Main(string[] args) { try { var parsed = Args.Parse(args); Console.WriteLine("You entered string '{0}' and int '{1}'", parsed.StringArg, parsed.IntArg); } catch (ArgException ex) { Console.WriteLine(ex.Message); Console.WriteLine(ArgUsage.GenerateUsageFromTemplate()); } } } ``` -------------------------------- ### Use custom completion source with [TabCompletion(typeof(MyCompletionSource))] Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Tells the [TabCompletion] attribute to use the custom completion source class MyCompletionSource for tab completion. ```csharp [TabCompletion(typeof(MyCompletionSource))] public class TestArgs { [ArgRequired] public string SomeParam { get; set; } public int AnotherParam { get; set; } } ``` -------------------------------- ### EncodeArgs class with action-specific arguments Source: https://github.com/adamabdelhamed/powerargs/wiki/Action-Framework Defines the arguments for the 'Encode' action. It includes a required source file (with [ArgExistingFile] and [ArgPosition(1)]), an optional output at position 2, an encoder with a default value of Encoder.Avi, and an ignored callback property. ```csharp public class EncodeArgs { [ArgRequired] [ArgExistingFile] [ArgPosition(1)] public string Source { get; set; } [ArgPosition(2)] public string Output { get; set; } [DefaultValue(Encoder.Avi)] public Encoder Encoder { get; set; } [ArgIgnore] public Action Callback { get; set; } } ``` -------------------------------- ### Define a multi-action calculator with PowerArgs Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Defines a calculator program with four actions (Add, Subtract, Multiply, Divide) using PowerArgs attributes. The Main method invokes the action based on the first command-line argument; invalid actions produce a friendly error and per-action validation is handled automatically. ```csharp [ArgExceptionBehavior(ArgExceptionPolicy.StandardExceptionHandling)] public class CalculatorProgram { [HelpHook, ArgShortcut("-?"), ArgDescription("Shows this help")] public bool Help { get; set; } [ArgActionMethod, ArgDescription("Adds the two operands")] public void Add(TwoOperandArgs args) { Console.WriteLine(args.Value1 + args.Value2); } [ArgActionMethod, ArgDescription("Subtracts the two operands")] public void Subtract(TwoOperandArgs args) { Console.WriteLine(args.Value1 - args.Value2); } [ArgActionMethod, ArgDescription("Multiplies the two operands")] public void Multiply(TwoOperandArgs args) { Console.WriteLine(args.Value1 * args.Value2); } [ArgActionMethod, ArgDescription("Divides the two operands")] public void Divide(TwoOperandArgs args) { Console.WriteLine(args.Value1 / args.Value2); } } public class TwoOperandArgs { [ArgRequired, ArgDescription("The first operand to process"), ArgPosition(1)] public double Value1 { get; set; } [ArgRequired, ArgDescription("The second operand to process"), ArgPosition(2)] public double Value2 { get; set; } } class Program { static void Main(string[] args) { Args.InvokeAction(args); } } ``` -------------------------------- ### Create custom completion source from SimpleTabCompletionSource Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Derives from SimpleTabCompletionSource to provide a list of words for tab completion. This is the easy way to add custom completion logic. ```csharp public class MyCompletionSource : SimpleTabCompletionSource { public MyCompletionSource() : base(MyCompletionSource.GetWords()) {} private static IEnumerable GetWords() { return new string[] { "SomeLongWordThatYouWantToEnableCompletionFor", "SomeOtherWordToEnableCompletionFor" }; } } ``` -------------------------------- ### Source-generated pipeline scaffold with partial properties Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Declare a scaffold and its public argument properties as partial to opt into source-generated property bodies and parsing metadata on .NET 10. All public properties declared by the scaffold, including [ArgIgnore] properties, must be partial; inherited public argument properties can remain ordinary. ```csharp public partial class MyGeneratedArgs { [ArgRequired] public partial string Input { get; set; } public partial int Count { get; set; } } ``` -------------------------------- ### Define and parse arguments with PowerArgs Source: https://github.com/adamabdelhamed/powerargs/wiki/Getting-Started Defines a simple argument class with required and existing-file validation, then parses command-line arguments using Args.Parse. The ArgRequired attribute makes the argument mandatory, and ArgExistingFile throws an ArgException if the provided path does not exist. ```csharp public class MyArgs { [ArgRequired] // This argument is required. Without this attribute, it would be optional. [ArgExistingFile] // If the user passes a string that is not an existing file path, an ArgException is thrown. public string StringArg { get; set; } } ``` ```csharp class Program { static void Main(string[] args) { var parsed = Args.Parse(args); Console.WriteLine("You entered StringArg '{0}'", parsed.StringArg); } } ``` -------------------------------- ### Custom reviver for Point type with [ArgReviverType] and [ArgReviver] Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Defines a custom reviver for the Point type. The class is marked with [ArgReviverType] and the static method Revive is marked with [ArgReviver]. PowerArgs automatically finds this reviver when it encounters a Point argument. The reviver parses strings in the format "x,y" and throws ArgException with a friendly message if the format is invalid. ```csharp [ArgReviverType] public class CustomReviverExample { // By default, PowerArgs does not know what a 'Point' is. So it will // automatically search your assembly for arg revivers that meet the // following criteria: // - Live in a class or struct with an [ArgReviverType] attribute // - Are a public, static method with an [ArgReviver] attribute // - Accepts exactly two string parameters // - The return value matches the type that is needed public Point Point { get; set; } // This ArgReviver matches the criteria for a "Point" reviver // so it will be called when PowerArgs finds any Point argument. // // ArgRevivers should throw ArgException with a friendly message // if the string could not be revived due to user error. [ArgReviver] public static Point Revive(string key, string val) { var match = Regex.Match(val, @"(\d*),(\d*)"); if (match.Success == false) { throw new ArgException("Not a valid point: " + val); } else { Point ret = new Point(); ret.X = int.Parse(match.Groups[1].Value); ret.Y = int.Parse(match.Groups[2].Value); return ret; } } } ``` -------------------------------- ### Use loose parameters in an action method Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Shows an action method that accepts loose parameters instead of a complex type. Useful for small programs where input parameters don't need to be reused across actions; cannot be mixed with the complex-type pattern. ```csharp [ArgActionMethod, ArgDescription("Adds the two operands")] public void Add( [ArgRequired][ArgDescription("The first value to add"), ArgPosition(1)] double value1, [ArgRequired][ArgDescription("The second value to add"), ArgPosition(2)] double value2) { Console.WriteLine(value1 + value2); } ``` -------------------------------- ### ClipArgs class inheriting from EncodeArgs with range attributes Source: https://github.com/adamabdelhamed/powerargs/wiki/Action-Framework Defines arguments for the 'Clip' action, inheriting from EncodeArgs and adding From and To properties with [ArgRange(0, 1000)] attributes. ```csharp public class ClipArgs : EncodeArgs { [ArgRange(0, 1000)] public double From { get; set; } [ArgRange(0, 1000)] public double To { get; set; } } ``` -------------------------------- ### Convert secure string to non-secure string Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Converts the secure string to a non-secure string. This is less secure but still hides user input on the command line. The conversion line prompts the user. ```csharp TestArgs parsed = Args.Parse(); string notSecure = parsed.Password.ConvertToNonsecureString(); // This line causes the user to be prompted ``` -------------------------------- ### PowerArgs with ArgExceptionBehavior and InvokeMain Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Shows a complete PowerArgs program with automatic exception handling. ArgException-derived exceptions are treated as user errors and display the message plus auto-generated usage; other exceptions bubble up. The non-static Main method is invoked after parsing and can access instance properties. ```csharp // A class that describes the command line arguments for this program [ArgExceptionBehavior(ArgExceptionPolicy.StandardExceptionHandling)] public class MyArgs { // This argument is required and if not specified the user will // be prompted. [ArgRequired(PromptIfMissing=true)] public string StringArg { get; set; } // This argument is not required, but if specified must be >= 0 and <= 60 [ArgRange(0,60)] public int IntArg { get; set; } // This non-static Main method will be called and it will be able to access the parsed and populated instance level properties. public void Main() { Console.WriteLine("You entered string '{0}' and int '{1}'", this.StringArg, this.IntArg); } } class Program { static void Main(string[] args) { Args.InvokeMain(args); } } ``` -------------------------------- ### Conditional template with {{if HasActions}} and {{ifnot HasActions}} Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Conditionally includes template fragments based on a property. If HasActions is true, outputs 'Global options'; otherwise outputs 'Options'. ```text {{if HasActions}}Global options!{{if}}{{ifnot HasActions}}Options!{{ifnot}}: ``` -------------------------------- ### EncodeArgs class with validation attributes Source: https://github.com/adamabdelhamed/powerargs/wiki/Other-argument-metadata Defines a class with properties decorated with PowerArgs attributes: [ArgRequired] and [ArgExistingFile] for the Source argument, [ArgPosition] for positional arguments, [DefaultValue] for an optional enum argument, and [ArgIgnore] to exclude a property from parsing. ```csharp public class EncodeArgs { [ArgRequired] [ArgExistingFile] [ArgPosition(1)] public string Source { get; set; } [ArgPosition(2)] public string Output { get; set; } [DefaultValue(Encoder.Avi)] public Encoder Encoder { get; set; } [ArgIgnore] public Action Callback { get; set; } } ``` -------------------------------- ### Add SecureStringArgument property Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Defines a property of type SecureStringArgument to support secure string arguments like passwords, preventing user input from being visible on the command line. ```csharp public class TestArgs { public SecureStringArgument Password { get; set; } } ``` -------------------------------- ### Access secure string value Source: https://github.com/adamabdelhamed/powerargs/blob/master/readme.md Accesses the secure string value from a parsed SecureStringArgument. The line accessing SecureString prompts the user for input. ```csharp TestArgs parsed = Args.Parse(); SecureString secure = parsed.Password.SecureString; // This line causes the user to be prompted ```