2017-03-06 140 views
2

我想寫一個腳本,需要檢測PowerShell模塊的ArgumentList是什麼。有什麼方法可以找到這個嗎?如何找出PowerShell模塊的ArgumentList?

最後的遊戲是能夠使用它創建一個簡單的DI容器來加載模塊。

+1

相關信息:[瞭解Windows PowerShell模塊](https://msdn.microsoft.com/en-us/library/dd878324(v = vs.85).aspx)和/或[使用Get-Command PowerShell Cmdlet查找參數集Information_](https://blogs.technet.microsoft.com/heyscriptingguy/2012/05/16/use-the-get-command-powershell-cmdlet-to-find-parameter-set-information/ ) – JosefZ

+1

您認爲「PowerShell模塊的參數列表」究竟是什麼?模塊通常沒有參數,只有它們公開的cmdlet可以執行。 –

+1

是的,他們通常沒有他們,但可以擁有他們。它只需要psm1文件中的參數部分。使用命令和函數,您可以檢查Get-Command中的參數屬性以獲取大量信息。似乎沒有任何模塊參數的等價物 –

回答

1

您可以使用AST分析器向您顯示模塊文件的param()塊。也許可以使用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返回的'Parameters'屬性。如果你想要屬性信息,你需要做一些工作來構建每一個。