简体   繁体   中英

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

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

I have a powershell script with the following parameters. I am executing this powershell script from C#. I would like to parse the script and get the parameters. In future the script may change and so will the parameter count.

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
}

I'd use the PowerShell Parser class for this. The following example is in PowerShell for convenience but it could easily be done in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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