Simplify Parameter Attributes

by Oct 16, 2015

If all of your systems run PowerShell 3.0 or better, you can start shortening function parameter attributes. Boolean attributes now all default to $true, so this would be the default code in PowerShell 2.0:

function Get-Sample
{
  Param
  (
    [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
    [string]
    $Name
  )
}

Beginning with PowerShell 3.0, it boils down to:

function Get-Sample
{
  Param
  (
    [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
    [string]
    $Name
  )
}

The latter is cleaner and shorter but will no longer run in PowerShell 2.0.

Twitter This Tip! ReTweet this Tip!