简体   繁体   English

解析powershell脚本参数

[英]Parse powershell script parameters

Is there an easy way to parse the params from a powershell script file 有没有一种简单的方法可以从powershell脚本文件中解析params

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? 我已经开始阅读该文件并想知道是否有更好的方法,可能是通过help / man命令?

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 : 第一个(imho更好):使用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. 我喜欢@stej提出的Get-Command解决方案。 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 . 在这种情况下,请查看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. 它将告诉您如何执行此操作,之后您可以在脚本/模块上使用Get-Help

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. 如果您about_functions_advanced_parameters更严格的参数处理,请查看about_functions_advanced_parametersabout_functions_cmdletbindings ,了解如何更好地构造参数。 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读取,仅允许来自给定集合的值,并在询问输入时给出简短的帮助消息(如果未给出该参数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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