【问题标题】:Using PowerShell Parser for console application将 PowerShell Parser 用于控制台应用程序
【发布时间】:2018-11-24 05:54:05
【问题描述】:

我较大的 PowerShell/控制台应用程序需要 OOP 等以便于开发。

我知道 NDesk.Options 和 CommandLineParser 之类的解析器,但我想要一些东西来尽可能接近地模拟 cmdlet 解析。例如。支持解析:

MyProject.exe do-thing ("computer1", "computer2") -p "parameter"
MyProject.exe do-thing -cn ("computer1", "computer2") -p "parameter" -verbose

是否可以使用System.Management.Automation.Language.Parser 或其他工具来模拟PowerShell 解析?有什么需要注意的例子和陷阱吗?

【问题讨论】:

    标签: powershell parsing automation console console-application


    【解决方案1】:

    当然,您可以使用Parser.ParseInput() 解析参数,然后从生成的CommandAst 中提取各个元素:

    using System.Management.Automation.Language;
    
    public class Program
    {
        public static void Main(string[] args)
        {
            Token[] tokens;
            ParseError[] errors;
            Ast topAst = Parser.ParseInput(String.Join(" ", args), out tokens, out errors);
    
            // Find the CommandAst object
            CommandAst parsedCommand = topAst.Find(ast => ast is CommandAst, true);
    
            // Grab the command name
            string commandName = ((StringConstantExpressionAst)parsedCommand.CommandElements[0]).Value;
    
            // Grab the remaining command arguments from CommandAst.CommandElements
        }
    }
    

    我可能会将参数存储在 Dictionary<string,string[]>

    【讨论】:

      猜你喜欢
      • 2016-06-15
      • 2010-12-22
      • 1970-01-01
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 2014-12-20
      • 2010-11-13
      相关资源
      最近更新 更多