Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse powershell script parameters

Tags:

powershell

Is there an easy way to parse the params from a powershell script file

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

I have started reading the file and wondered if there is a better way, maybe by a help/man command?

class PowerShellParameter {
    public string Name;
    public string Type;
    public string Default;
}

string[] lines = File.ReadAllLines(path);
bool inparamblock = false;
for (int i = 0; i < lines.Length; i++) {
    if (lines[i].Contains("param")) {
        inparamblock = true;
    } else if (inparamblock) {
        new PowerShellParameter(...)
        if (lines[i].Contains(")")) {
            break;
        }
    }
}
like image 263
djeeg Avatar asked Feb 25 '23 17:02

djeeg


1 Answers

There are at least two possibilies. First one (imho better): use Get-Command:

# my test file
@'
param(
  $p1,
  $p2
)

write-host $p1 $p2
'@ | Set-content -path $env:temp\sotest.ps1
(Get-Command $env:temp\sotest.ps1).parameters.keys

For all members look at

Get-Command $env:temp\sotest.ps1 | gm
#or
Get-Command $env:temp\sotest.ps1 | fl *

The other (harder way) is to use regular expression

[regex]::Matches((Get-Help $env:temp\sotest.ps1), '(?<=\[\[-)[\w]+') | select -exp Value
like image 181
stej Avatar answered Mar 06 '23 22:03

stej