繁体   English   中英

解析Powershell脚本的参数。 如何从C#中做到这一点?

[英]Parsing Parameters of a Powershell Script. How to do this from C#?

param(
    [string]$name,
    [string]$template
)

我有一个带有以下参数的powershell脚本。 我正在从C#执行这个powershell脚本。 我想解析脚本并获取参数。 将来脚本可能会更改,参数计数也会更改。

var str = @"param([string]$name,[string]$template)";
var matches = Regex.Matches(str, "\\[(?<type>\\w+)\\]\\$(?<name>\\w+)").OfType<Match>()
                   .Select(m => new 
                                {
                                   name = m.Groups["name"].Value, 
                                   type = m.Groups["type"].Value
                                });
foreach (var m in matches)
{
    // check m.name and m.type
}

我将使用PowerShell Parser类。 为方便起见,以下示例在PowerShell中,但可以在C#中轻松完成:

PS> $str = 'param([string]$name,[string]$template)'
PS> $ast = [System.Management.Automation.Language.Parser]::ParseInput($str, [ref]$null, [ref]$null)
PS> $ast.ParamBlock.Parameters.Name.Extent.Text
$name
$template

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM