When my cmhelet powershell parameter is set to ValueFromPipelineByPropertyName and I have an alias, how do I get the original property name?

How can a function say whether a parameter was passed as an alias or an object in a pipeline property was mapped as an alias? How to get the original name?

Suppose my Powershell cmdlet accepts pipeline input and I want to use ValueFromPipelineByPropertyName. I have an alias because I can get several different types of objects, and I want to be able to do something a little different depending on what I get.

This does not work

function Test-DogOrCitizenOrComputer
{
    [CmdletBinding()]
    Param
    (
        # Way Overloaded Example
        [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [Alias("Country", "Manufacturer")] 
        [string]$DogBreed,

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [string]$Name

    )
    # For debugging purposes, since the debugger clobbers stuff
    $foo = $MyInvocation
    $bar = $PSBoundParameters

    # This always matches.
    if ($MyInvocation.BoundParameters.ContainsKey('DogBreed')) {
        "Greetings, $Name, you are a good dog, you cute little $DogBreed"
    }
    # These never do.
    if ($MyInvocation.BoundParameters.ContainsKey('Country')) {
        "Greetings, $Name, proud citizen of $Country"
    }
    if ($MyInvocation.BoundParameters.ContainsKey('Manufacturer')) {
        "Greetings, $Name, future ruler of earth, created by $Manufacturer"
    }

}

Performing it, we see problems

Firstly, it works:

PS> Test-DogOrCitizenOrComputer -Name Keith -DogBreed Basset
Greetings, Keith, you are a good dog, you cute little Basset

The problem is obvious when we try to execute Alias:

PS> Test-DogOrCitizenOrComputer -Name Calculon -Manufacturer HP
Greetings, Calculon, you are a good dog, you cute little HP

Bonus does not work, does not work on the pipeline:

PS> New-Object PSObject -Property @{'Name'='Fred'; 'Country'='USA'} | Test-DogOrCitizenOrComputer
Greetings, Fred, you are a good dog, you cute little USA

PS> New-Object PSObject -Property @{'Name'='HAL'; 'Manufacturer'='IBM'} | Test-DogOrCitizenOrComputer
Greetings, HAL, you are a good dog, you cute little IBM

$MyInvocation.BoundParameters $PSBoundParameters , , . , .

, PowerShell "" , , "" , . , , , ( , ).

, , ? ?

+4
1

, , Alias, . , .

, - , , , , .

, , ValueFromPipelineByPropertyName, , .

(, , ..). ( ).

+4

Source: https://habr.com/ru/post/1683545/


All Articles