Home Best Practice Functions Use param() Blocks
 

Use param() Blocks

There are actually two ways how you can define function parameters. One approach uses a syntax similar to traditional scripting languages like VBScript. This would define a function called Test-Connectivity with two parameters: -ComputerName and -UserName:

  

function Test-Connectivity ($ComputerName, $UserName)
{

  "You entered '$ComputerName' and '$UserName'"
}

  Simplified parameter definition

Better: Use a param() Block

Internally, PowerShell would convert the above function to a different syntax, using a param() block inside the function body to define the parameters. Since the function would be converted anyway, this is one of the reasons why it is best practice to use a param() block in the first place:

  

function Test-Connectivity
{
   param
   (
     $ComputerName,

     $UserName
   )

  "You entered '$ComputerName' and '$UserName'"
}

  Always make sure you define parameters with a param() block

Why param() blocks are more consistent

While both approaches are technically ok, the latter approach, using the param() block, is much more consistent. You can easily turn your function into a script that still supports the same set of parameters, simply by stripping the function body:

  

param
(
  $ComputerName,
 
  $UserName
)

"You entered '$ComputerName' and '$UserName'"

  Turning a function into a script with parameters

So the very same param() block can be used to define script parameters. If you saved this script as "test.ps1", you could then call it with the parameters you defined:

PS> C:\temp\test.ps1 –ComputerName server12 –UserName tobias

  param() blocks work consistently in functions and scripts

Using param() in ScriptBlocks

You can even use param() blocks in plain vanilla unnamed PowerShell scriptblocks, so they are really a core PowerShell language feature:

  

$code = {
  param
  (
    $ComputerName,
   
    $UserName
  )
 
 
  "You entered '$ComputerName' and '$UserName'"
}

& $code -ComputerName test -UserName tobias

  param() blocks even work inside of unnamed scriptblocks

When you run this code, the parameters are automatically received by the scriptblock that used the param() block.