开发者

Parse powershell script parameters

开发者 https://www.devze.com 2023-02-20 04:39 出处:网络
Is there an easy way to parse the params from a powershell script file param( [string]$name, [string]$template

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


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


I like the solution with Get-Command proposed by @stej. Unfortunately it does not work if script parameters have explicit types specified and an assembly of such a type is not yet loaded into the session. That is why I still use this script: Get names of script parameters


I'm not really sure what you're after, is it documenting your scripts? In that case have a look at Get-Help about_Comment_Based_Help. It will tell you how to do that, and after that you can use Get-Help on your script/module.

If you're after more strict parameter handling, take a look at about_functions_advanced_parameters and about_functions_cmdletbindings on how to better structure parameters. For example,

[Parameter(Position=0,Mandatory=$true,HelpMessage='Enter architecture("OSX","WinXP","Win7","Linux")')] [ValidateSet("OSX","WinXP","Win7","Linux")] [string]$architecture

will make that parameter mandatory, read from position 0 of the command, allow only a value from the given set, and give a brief help message when asking for input if that parameter was not given.

0

精彩评论

暂无评论...
验证码 换一张
取 消