1
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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1
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
}

10 Comments

the OP says In future the script may change and so will the parameter count. ???
@K.B. this code grab all params of type [type]$name, independent from param count
ok well but what if the params type change [integer] for example it will not work right ?
huuuum give it a try
param([integer]$name,[string]$template) you mean? just checked, it works
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.