Impossibile generare ParametriSetMetadata durante la creazione a livello di codice di un blocco parametri

StackOverflow https://stackoverflow.com/questions/2466210

Domanda

Sto cercando di creare a livello di codice un blocco di parametri per una funzione (sulla falsariga di questo post del blog ).

Sto iniziando con a CommandMetadata oggetto (da una funzione esistente).Posso creare il Metadati dei parametri oggetto e impostare cose come il Parametro, il nome e alcuni attributi.

Il problema che sto riscontrando è che quando utilizzo il file Metodo GetParamBlock della classe ProxyCommand, nessuno dei miei attributi che ho impostato nella raccolta Attributes di ParametroMetadata viene generato.

Il problema che ciò causa è che quando viene chiamato GetParamBlock, il nuovo parametro non viene annotato con l'attributo Parametro appropriato.

Esempio:

function test 
{
    [CmdletBinding()]
    param (
    [Parameter()]
    $InitialParameter)

    Write-Host "I don't matter."
}

$MetaData = New-Object System.Management.Automation.CommandMetaData (get-command test)

$NewParameter = New-Object System.Management.Automation.ParameterMetadata 'NewParameter'

$NewParameter.ParameterType = [string[]]

$Attribute = New-Object System.Management.Automation.ParameterAttribute 
$Attribute.Position = 1
$Attribute.Mandatory = $true
$Attribute.ValueFromPipeline = $true

$NewParameter.Attributes.Add($Attribute)
$MetaData.Parameters.Add('NewParameter', $NewParameter)


[System.Management.Automation.ProxyCommand]::GetParamBlock($MetaData) 
È stato utile?

Soluzione

function test 
{
    [CmdletBinding()]
    param (
    [Parameter()]
    $InitialParameter)

    Write-Host "I don't matter."
}

$MetaData = New-Object System.Management.Automation.CommandMetaData (get-command test)

$NewParameter = New-Object System.Management.Automation.ParameterMetadata 'NewParameter'

$NewParameter.ParameterType = [string[]]

$Attribute = New-Object System.Management.Automation.ParameterAttribute 
$Attribute.Position = 1
$Attribute.Mandatory = $true
$Attribute.ValueFromPipeline = $true

$NewParameter.Attributes.Add($Attribute)
$MetaData.Parameters.Add('NewParameter', $NewParameter)

$ParameterSetMetadata = "System.Management.Automation.ParameterSetMetadata"
$ParameterSetInfo = new-object psobject -Property @{ 
    Position=[Int]::MinValue
    Flags=3
    HelpMessage="Please Enter a Value"
} | ForEach { 
    $_.PSTypeNames.Add("Deserialized.$ParameterSetMetadata")
    write-Output $_ 
}

$converter = new-object  Microsoft.PowerShell.DeserializingTypeConverter
$ConvertedSet = $converter.ConvertFrom($ParameterSetInfo,$ParameterSetMetadata, $null, $true)

$NewParameter.ParameterSets.Add('__AllParameterSets', $ConvertedSet )

[System.Management.Automation.ProxyCommand]::GetParamBlock($MetaData)

Altri suggerimenti

Il motivo per cui non è arrivato è perché il vostro NewParameter ha bisogno di appartenere ad almeno un set di parametri. In questo caso, dovrebbe essere un membro del Parameterset speciale "__AllParameterSets".

È possibile verificare questo copiando l'istanza ParameterSetMetadata da InitialParameter. Unfortuntely Non riesco a vedere immediatamente come ottenere questo ParameterSetMetadata se non si dispone di alcun parametro per afferrare da. Copiandolo dalla altro parametro fa apparire nell'output, ma è i metadati da InitialParameter, quindi questa non è la soluzione, solo il motivo per cui non funziona (ancora). Io aggiornerò questo post quando vedo io fuori.

-Oisin

sbraitare su:Ero anche molto, molto arrabbiato per il fatto che possiamo istanziare un tipo di System.Management.Automation.ParameterMetadata ma non possiamo inizializzarlo.Microsoft distrugge gran parte del divertimento della libreria di classi vincolando le classi mediante l'uso di classi private, interne o sigillate......lo usano spesso e senza alcuna ragione immaginabile.Questo è un design di libreria davvero pazzesco!sbraitare:

Per la metaprogrammazione e per creare ProxyCommands (funzioni proxy) avevo la necessità di creare da zero un parametro di Windows PowerShell in modo programmatico.Non mi piace nemmeno irrompere nelle lezioni, rubare e usare cose proibite, che sono soggette a modifiche.Anche il trucco della serializzazione è lo stesso modo sporco per fare la stessa cosa su un percorso diverso.

ecco il mio prototipo di soluzione.Sto creando una funzione con un parametro come testo (codice sorgente della funzione).il mio primo tentativo è stato quello di eseguire una funzione New-Item:\ -value {code} nell'unità della funzione e quindi eseguire un comando Get sulla nuova funzione per estrarre i metadati.Ma questo risulta che la funzione era solo un cavallo morto.Non è stato compilato.Quindi ho dovuto utilizzare Invoke-Expression per "compilare" il codice sorgente della funzione.

Function New-Parameter {

    [CmdletBinding()]
    param(
        [Switch]$Mandatory,
        [UInt32]$Position,
        [Switch]$ValueFromPipeline,
        [Switch]$ValueFromPipelineByPropertyName,
        [Switch]$ValueFromRemainingArguments,
        [String]$HelpMessage,

        [Type]$Type=[Type]'System.Management.Automation.SwitchParameter',
        [Parameter(Mandatory=$True)]
        [String]$Name,
        [String]$DefaultValue,

        [Switch]$DontShow,

        [String[]]$ParameterSetName,
        [String[]]$Aliases,
        # if Metadata is present the result is an System.Management.Automation.ParameterMetadata object
        # If Metadata is absent the sourcecode for the Parameter is returned
        [Switch]$Metadata
    )

    $ParameterAttrib = [System.Collections.ArrayList]@()

    # using GUID to create an unique function Name
    $Guid = ([Guid]::NewGuid()).ToString()

    # using a StringBuilder to glue the sourcecode 
    $stringBuilder = New-Object System.Text.StringBuilder

        If($Metadata.IsPresent) {

        # Open the Function{} block
        [Void]$stringBuilder.AppendLine("Function $Guid {")

        # add the [CmdletBinding()] attribute 
        [Void]$stringBuilder.AppendLine("[CmdletBinding()]")

        # Open the Param() block
        [Void]$stringBuilder.AppendLine("param(")
    } 

    # query if we have one or more ParameterSetName
    $ParmameterSetNameCount = 0
    If(-not [String]::IsNullOrEmpty($ParameterSetName)) {
        $ParmameterSetNameCount = @($ParameterSetName).Count
    } 

    # Open the [Parameter()] attribut
    [Void]$stringBuilder.Append('[Parameter(')

    If($Mandatory.IsPresent) {
        [Void]$ParameterAttrib.Add('Mandatory=$True')
    }
    If($Position) {
        [Void]$ParameterAttrib.Add("Position=$Position")
    }
    If($ParmameterSetNameCount -gt 0){
            # in the first full blown [Parameter()] attribut allways insert the first ParametersetName
            [Void]$ParameterAttrib.Add("ParameterSetName='$($ParameterSetName[0])'")  
    }


    If($ValueFromPipeline.IsPresent) {
        [Void]$ParameterAttrib.Add('ValueFromPipeline=$True')
    }
    If($ValueFromPipelineByPropertyName.IsPresent) {
        [Void]$ParameterAttrib.Add('ValueFromPipelineByPropertyName=$True')
    }
    If($ValueFromRemainingArguments.IsPresent) {
        [Void]$ParameterAttrib.Add('ValueFromRemainingArguments=$True')
    }
    If($DontShow.IsPresent) {
        If($PSVersionTable.PSVersion.Major -lt 4) {
            Write-Warning "The 'DontShow' attribute requires PowerShell 4.0 or above! `n Supressing the 'DontShow' attribute!"
        } Else {
            [Void]$ParameterAttrib.Add('DontShow')
        }

    }
    If(-not [String]::IsNullOrEmpty($HelpMessage)) {
        [Void]$ParameterAttrib.Add("HelpMessage='$HelpMessage'")
    }

    # generate comma separated list from array
    [Void]$stringBuilder.Append("$($ParameterAttrib -Join ',')")

    $ParameterAttrib.Clear()

    # close the [Parameter()] attribut
    [Void]$stringBuilder.AppendLine(")]")
    $ParmameterSetLoopCounter++

    # If we have more then one ParametersetName
    IF($ParmameterSetNameCount -gt 1) {
        # add remaining parameterset names the parameter belongs to
        for ($i = 1; $i -lt $ParmameterSetNameCount; $i++) { 
            [Void]$stringBuilder.AppendLine("[Parameter(ParameterSetName='$($ParameterSetName[$i])')]")  
        }  
    }

    # Create Alias Attribute from Aliases
    If(-not [String]::IsNullOrEmpty($Aliases)) {
        [Void]$stringBuilder.AppendLine("[Alias('$($Aliases -join "','")')]")
    }

    # add Parameter Type
    [Void]$stringBuilder.Append("[$($Type.Fullname)]")

    # add the Parameter Name
    [Void]$stringBuilder.Append("`$$Name")

        If(-not [String]::IsNullOrEmpty($ParameterSetName)) {
        [Void]$stringBuilder.Append("=$DefaultValue")
        }

    If($Metadata.IsPresent) {
        # close the Param() block
        [Void]$stringBuilder.AppendLine()
        [Void]$stringBuilder.AppendLine(')')

        # close the Function block
        [Void]$stringBuilder.AppendLine('}')
    }

    # return the result
    If($Metadata.IsPresent) {
        # if we have to return a ParameterMetadata Object we create a temporary function
        # because you can instatiate a ParameterMetadata Object but most of the Properties are constrained to get only and not to set!

        # Create and 'compile' the function into the function: drive
        Invoke-Expression ($stringBuilder.ToString())

        # from the temporary function we query the the ParameterMetadata and
        # return theParameterMetadata Object
        (Get-Command -Name $Guid -CommandType Function).Parameters.$Name

        # remove the Function from Function: drive
        $Null = Remove-Item Function:\$Guid -Force

    } Else {
        # return the sourcecode of the Parameter
        Write-Output $stringBuilder.ToString()
    }

}

#Example calls:

# without Parametersets
New-Parameter -Name 'Param1' -Mandatory -Position 3 -ValueFromPipeline -ValueFromPipelineByPropertyName -ValueFromRemainingArguments -HelpMessage "Give me hope Joana!" -Type 'System.String' -Aliases 'Ali1','Ali2','Ali3' -DontShow -DefaultValue 34
New-Parameter -Name 'Param1' -Mandatory -Position 3 -ValueFromPipeline -ValueFromPipelineByPropertyName -ValueFromRemainingArguments -HelpMessage "Give me hope Joana!" -Type 'System.String' -Aliases 'Ali1','Ali2','Ali3' -DontShow -DefaultValue 34 -Metadata

# with Parametersets
New-Parameter -Name 'Param1' -Mandatory -Position 3 -ValueFromPipeline -ValueFromPipelineByPropertyName -ValueFromRemainingArguments -HelpMessage "Give me hope Joana!" -Type 'System.String' -ParameterSetName 'Snover','Payette' -Aliases 'Ali1','Ali2','Ali3' -DontShow -DefaultValue 34
New-Parameter -Name 'Param1' -Mandatory -Position 3 -ValueFromPipeline -ValueFromPipelineByPropertyName -ValueFromRemainingArguments -HelpMessage "Give me hope Joana!" -Type 'System.String' -ParameterSetName 'Snover','Payette' -Aliases 'Ali1','Ali2','Ali3' -DontShow -DefaultValue 34 -Metadata

SONO FATTO BENE A COSTRUIRE I PARAMETRI?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top