cdmihai
cdmihai

Reputation: 3028

How to make powershell emit an error on undeclared command line arguments

Given the following script.ps1

Param([switch]$Foo)

Write-Output $Foo

How can I make it error on undeclared arguments, such as script.ps1 -Bar?

I can write my own code to do it by interpreting $args, but it seems like powershell should be able to do it for me, as it already parses the arguments.

Upvotes: 1

Views: 122

Answers (1)

mklement0
mklement0

Reputation: 437448

In order to only accept declared parameters and error on unexpected extra arguments, you must make your script/function an advanced one, which can be achieved as follows:

  • explicitly: decorate the param(...) block with a [CmdletBinding(...)] attribute.

  • implicitly: decorate any of the individual parameters with a [Parameter(...)] attribute.

For instance (using a script block ({ ... }) for simplicity; the same applies to scripts and functions):

PS> & { Param([switch] $Foo)  } -Bar
# !! NO error (or output) - undeclared -Bar switch is quietly IGNORED.

# Using the [CmdletBinding()] attribute ensures that only declared
# parameters can be used.
PS> & { [CmdletBinding()] Param([switch] $Foo)  } -Bar
A parameter cannot be found that matches parameter name 'Bar'. # OK - error.
...

See Get-Help about_Functions_Advanced

Upvotes: 2

Related Questions