15

Is there any reason to use the "Param( ... )" construction inside a function definition?

My understanding is that you should use this for specifying parameters to scripts (and scriptblocks). I see a lot of examples on the web with parameters listed this way instead of just listing the parameters after the function name.

Example:

function Foo([string]$Bar){
   #Body of function
}

Or,

function Foo{
     Param([string]$Bar)

}
3
  • Maybe someone has a better answer, but I'm casting my vote as "it's entirely a matter of taste." Commented May 15, 2009 at 18:52
  • Found this which suggests you're right: vistax64.com/powershell/… Commented May 15, 2009 at 21:23
  • Edited question to include scriptblocks. Commented May 19, 2009 at 2:56

4 Answers 4

19

In V1, it really is just a preference. Using the param statement has traditionally been more formal, but functionally it's the same thing.

You will probably see a lot more use of PARAM in PowerShell V2 because of the ability to add attributes to parameters, similar to attributes in C#.

param
(
[Parameter( Mandatory=$true,
            Position=0,
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true)]
[Alias("name")]
[String]
$path
)

Here you can specify the parameter attribute and a bunch of arguments to that attribute. You can also specify aliases and a number of other validation requiremets.

Keith makes a couple of great points as well. You can use the param statement to pass parameters to annonymous scriptblocks (lambda expressions) or to a PS1 script.

Sign up to request clarification or add additional context in comments.

Comments

6

param() is required to specify the parameters for a script file and for scriptblocks:

PS> $sb = {param($x,$y) $x + $y}
PS> &$sb 1 3
4

Having it also be available for traditional functions is just a consistency thing IMO. It is nicer for advanced functions which tend to have a lot of baggage, er metadata, per parameter.

Comments

1

Possibly as a consistency measure? Always specifying parameters the same way improves readability.

Comments

-2

Param is a function that is used to extract the value of a form variable that is passed to your program (can be Perl or any scripting language probably that uses CGI).

For example, in an XHTML form, when you use an input element (tag) and specify the type to be "text" you wil also use a parameter called "name". name is given a value, say num, and this value should be the parameter for the param function so that it can extract the value that the user enters in the textbox in your form.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.