gpt4 book ai didi

powershell - 如何找出 PowerShell 模块的 ArgumentList?

转载 作者:行者123 更新时间:2023-12-02 23:57:02 25 4
gpt4 key购买 nike

我正在尝试编写一个脚本,该脚本需要检测 PowerShell 模块的 ArgumentList 是什么。有什么办法可以找出来吗?

最终游戏是能够使用它来创建一个简单的 DI 容器来加载模块。

最佳答案

您可以使用 AST 解析器向您展示模块文件的 param() block 。也许使用 Get-Module 来查找有关模块文件所在位置的信息,然后解析这些并遍历 AST 以获取您所追求的信息。这看起来像是有用的东西吗?

function Get-ModuleParameterList {
[CmdletBinding()]
param(
[string] $ModuleName
)

$GetModParams = @{
Name = $ModuleName
}

# Files need -ListAvailable
if (Test-Path $ModuleName -ErrorAction SilentlyContinue) {
$GetModParams.ListAvailable = $true
}

$ModuleInfo = Get-Module @GetModParams | select -First 1 # You'll have to work out what to do if more than one module is found

if ($null -eq $ModuleInfo) {
Write-Error "Unable to find information for '${ModuleName}' module"
return
}

$ParseErrors = $null
$Ast = if ($ModuleInfo.RootModule) {
$RootModule = '{0}\{1}' -f $ModuleInfo.ModuleBase, (Split-Path $ModuleInfo.RootModule -Leaf)

if (-not (Test-Path $RootModule)) {
Write-Error "Unable to determine RootModule for '${ModuleName}' module"
return
}

[System.Management.Automation.Language.Parser]::ParseFile($RootModule, [ref] $null, [ref] $ParseErrors)
}
elseif ($ModuleInfo.Definition) {
[System.Management.Automation.Language.Parser]::ParseInput($ModuleInfo.Definition, [ref] $null, [ref] $ParseErrors)
}
else {
Write-Error "Unable to figure out module source for '${ModuleName}' module"
return
}

if ($ParseErrors.Count -ne 0) {
Write-Error "Parsing errors detected when reading RootModule: ${RootModule}"
return
}

$ParamBlockAst = $Ast.Find({ $args[0] -is [System.Management.Automation.Language.ParamBlockAst] }, $false)

$ParamDictionary = [ordered] @{}
if ($ParamBlockAst) {
foreach ($CurrentParam in $ParamBlockAst.Parameters) {
$CurrentParamName = $CurrentParam.Name.VariablePath.UserPath
$ParamDictionary[$CurrentParamName] = New-Object System.Management.Automation.ParameterMetadata (
$CurrentParamName,
$CurrentParam.StaticType
)

# At this point, you can add attributes to the ParameterMetaData instance based on the Attribute

}
}
$ParamDictionary
}

您应该能够给它一个模块名称或模块的路径。它几乎没有经过测试,所以在某些情况下它可能不起作用。现在,它返回一个字典,就像查看从 Get-Command 返回的“参数”属性一样。如果你想要属性信息,你需要做一些工作来构建每个。

关于powershell - 如何找出 PowerShell 模块的 ArgumentList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42625366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com