powershell - 解析powershell脚本参数

标签 powershell

有没有一种简单的方法可以从 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/

相关文章:

powershell - 从Write-Host到其他命令的管道输出

powershell - 如何在 powershell 中创建函数原型(prototype)?

PowerShell 功能和性能

.net - 用于返回计算机上 .NET Framework 版本的 PowerShell 脚本?

powershell - 在PowerShell中使用全局变量的最佳方法?

windows - 远程运行 RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry 进行打印机设置更新

powershell - 将冒号分隔的字符串转换为 PowerShell 字典

PowerShell 模块 - 每个 cmdlet 都有单独的文件

mysql - 使用 PowerShell 3 连接到 MySQL 数据库

powershell - Azure AD 模块和 MS Online 模块有什么区别