1

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) }}
2
  • 4
    Don't use brackets around the parameters for your function and also remove the comma in between: Expression={ somefunkystuff $_.MyName $_.Number}}, then just have it return the values $p1 and $p2 Commented Feb 3, 2024 at 16:02
  • 1
    In short: PowerShell functions, cmdlets, scripts, and external programs must be invoked like shell commands - foo arg1 arg2 - not like C# methods - foo('arg1', 'arg2'). If you use , to separate arguments, you'll construct an array that a command sees as a single argument. Commented Feb 3, 2024 at 16:34

1 Answer 1

2

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

and change your code to:

  • return $p1[0].ToString() + $p1[1].ToString() changed to return $p1 + $p2
  • Expression={ somefunkystuff( $_.MyName, $_.Number) } change to Expression={ somefunkystuff $_.MyName $_.Number }
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
Sign up to request clarification or add additional context in comments.

1 Comment

thank you (certainly for the reference to the other post!)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.