powershellselect-object

powershell select-object expression with a function with parameters


how can i pass 2 parameters to a function in an expression?

function somefunkystuff ($p1, $p2)
{
    #both passed values are available, just not as expected
    #why are the parameters in the calling Expression passed to $p1 as an array instead of just to both parameters $p1 and $p2?
    #return $p1.ToString() + $p2.ToString() # doesn't work as expected

    return $p1[0].ToString() + $p1[1].ToString()
    
}
$a = [PSCustomObject]@{MyName="jef"; Number=1}
$b = [PSCustomObject]@{MyName="john"; Number=2}
$c = [PSCustomObject]@{MyName="jonas"; Number=3}

@($a, $b, $c) | Select-Object MyName, Number, @{Name="NameId"; Expression={ somefunkystuff( $_.MyName, $_.Number) }}

Solution

  • see: How do I pass multiple parameters into a function in PowerShell?

    and change your code to:

    function somefunkystuff ($p1, $p2)
    {
        #both passed values are available, just not as expected
        #why are the parameters in the calling Expression passed to $p1 as an array instead of just to both parameters $p1 and $p2?
        #return $p1.ToString() + $p2.ToString() # doesn't work as expected
    
        return $p1 + $p2
        
    }
    $a = [PSCustomObject]@{MyName="jef"; Number=1}
    $b = [PSCustomObject]@{MyName="john"; Number=2}
    $c = [PSCustomObject]@{MyName="jonas"; Number=3}
    
    @($a, $b, $c) | Select-Object MyName, Number, @{Name="NameId"; Expression={ somefunkystuff  $_.MyName $_.Number }}
    

    output:

    MyName Number NameId
    ------ ------ ------
    jef         1 jef1
    john        2 john2
    jonas       3 jonas3