2

I'm a PowerShell newbie and I've got stuck on something very simple. I am trying to create a variable that use placeholders ({0}{1}...) using string format (-f). The place holder variables are passed as parameters to the function that builds/formats the string. Unfortunately, the place holders remain blank.

Here's my code:

function SendName(){
  BuildReport $MyInvocation.MyCommand, 1, 2
}

Function BuildReport($functionName, $param1, $param2){    
    $report="You are in {0}. Parameter expected is {1}. Actual parameter is {2}" -f $functionName, $param1, $param2
    write-host $report
}

SendName

The output I get is:

You are in System.Object[]. Parameter expected is . Actual parameter is

1 Answer 1

2

You have to omit the comma (,) where you invoke the BuildReport method:

BuildReport $MyInvocation.MyCommand 1 2

Otherwise you will pass an array as the first parameter and $param1 and $param2 won't get populated.

The Output will be:

You are in SendName. Parameter expected is 1. Actual parameter is 
2
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Martin that's brilliant. SB
To explain further: PowerShell parameters are passed to functions using spaces, not commas. Commas are valid syntactically but wrong semantically - as Martin pointed out, using commas passes an array (which is not what you intended).
@user9850983 If an answer was helpful, it's best practice to up vote it or accept it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.