Question:
Is there an easy way to parse the params from a powershell script file
1 2 3 4 5 |
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?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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; } } } |
Answer:
There are at least two possibilies. First one (imho better): use Get-Command
:
1 2 3 4 5 6 7 8 9 10 11 |
# 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
1 2 3 4 |
Get-Command $env:temp\sotest.ps1 | gm #or Get-Command $env:temp\sotest.ps1 | fl * |
The other (harder way) is to use regular expression
1 2 |
[regex]::Matches((Get-Help $env:temp\sotest.ps1), '(?<=\[\[-)[\w]+') | select -exp Value |