有没有一种简单的方法可以从 powershell 脚本文件中解析参数
param(
[string]$name,
[string]$template
)
我已经开始阅读文件并想知道是否有更好的方法,也许是通过 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;
}
}
}
最佳答案
至少有两种可能。第一个(恕我直言更好):使用 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
为所有成员看
Get-Command $env:temp\sotest.ps1 | gm
#or
Get-Command $env:temp\sotest.ps1 | fl *
另一种(更难的方法)是使用正则表达式
[regex]::Matches((Get-Help $env:temp\sotest.ps1), '(?<=\[\[-)[\w]+') | select -exp Value
关于powershell - 解析powershell脚本参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5427799/