【问题标题】:How to discover PowerShell Script parameters in c#如何在 C# 中发现 PowerShell 脚本参数
【发布时间】:2014-10-15 19:47:30
【问题描述】:

我们希望在数据库中存储和管理 PowerShell 脚本并通过 C# 执行它们。 我们怎样才能在执行之前发现这样一个脚本的参数呢?因此我们可以将它们设置为已知值或提示用户输入值。

一些澄清:

我们创建了一个管理系统 MS。

  1. 管理员将 PowerShell 脚本存储在 MS 数据库中。
  2. 稍后,其他管理员从 MS 提供的列表中选择了此脚本。
  3. MS 发现脚本的参数。
  4. MS 提示管理员输入值。
  5. MS 使用提供的参数执行脚本。

        string testScript = @"
            {
                param(
                    [ValidateNotNullOrEmpty()]
                    [string]$Name
                )
                get-process $name
            ";
    
    Dictionary<string,object> DiscoverParameters()
    {
        using (PowerShell psi = PowerShell.Create())
        {
            psi.AddScript(testScript);
            var pars = new Dictionary<string,object>();
            //How do we get at the parameters
            return pars;
        }
    }
    
    void ExecuteScript(Dictionary<string,object> pars)
    {
        using (PowerShell psi = PowerShell.Create())
        {
            psi.AddScript(testScript);
            pars.ToList().ForEach(p => psi.AddParameter(p.Key, p.Value));
            Collection<PSObject> PSOutput = psi.Invoke();
            //...
        }
    }
    

【问题讨论】:

    标签: c# powershell


    【解决方案1】:

    mjolinor 是正确的,使用 PowerShell 解析器可能是获取参数的最佳方式。该示例在 PowerShell 中,下面是 C# 中的示例。我不太确定你在寻找什么参数是Dictionary&lt;string, object&gt;。在这里,我们只是将名称粘贴到列表中,尽管您可以提取其他信息,例如静态类型。

    using System.Management.Automation;
    using System.Management.Automation.Language;
    
    static void Main(string[] args)
    {
        const string testScript = @"
        param(
            [ValidateNotNullOrEmpty()]
            [string]$Name
        )
        get-process $name
    ";
        foreach(var parameter in GetScriptParameters(testScript))
        {
            Console.WriteLine(parameter);
        }
    }
    
    private static List<string> GetScriptParameters(string script)
    {
        Token[] tokens;
        ParseError[] errors;
        var ast = Parser.ParseInput(script, out tokens, out errors);
        if (errors.Length != 0)
        {
            Console.WriteLine("Errors: {0}", errors.Length);
            foreach (var error in errors)
            {
                Console.WriteLine(error);
            }
            return null;
        }
    
        return ast.ParamBlock.Parameters.Select(p => p.Name.ToString()).ToList();
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用PS解析器,并通过AST访问参数信息:

      $scriptfile = '<full path to script file>'
      $AST = [System.Management.Automation.Language.Parser]::ParseFile( $scriptfile,[ref]$null,[ref]$null)
      
      $AST.ParamBlock.Parameters | ft
      

      【讨论】:

        猜你喜欢
        • 2013-03-23
        • 2021-10-11
        • 1970-01-01
        • 2020-09-04
        • 2012-05-05
        • 2012-05-02
        • 1970-01-01
        • 1970-01-01
        • 2020-04-04
        相关资源
        最近更新 更多