To pass an argument to a powershell script

For named parameters, first line in the script has to be a param declaration:


or to declare multiple named parameters


Then you can do validation and handle gracefully, for example

if ($comment -eq "") {
    write-host "you must give a comment"

A simple if brutal way to bail if a required argument was not specified

param ( [string]$comment = $(throw "Please specify a comment" ))

Can also use a type of boolean parameter called a switch


Then $IsGood will be $false, unless the parameter was specified

".\script1.ps1"                 #  $IsGood = $false
".\script1.ps1 -IsGood"         #  $IsGood = $true
".\script1.ps1 -isGood:$true"   #  $IsGood = $true
".\script1.ps1 -isGood:$false"  #  $IsGood = $false

Don't like named parameters? Fine! Use positional...

$height=$args[1] it's 1999.

Validate the parameters...

But if you do use real params you can also enforce simple validation:

For example -- string, length from 1 to 10...


Or how about a number that must be within a range...

Param( [ValidateRange(0,10)][int]$integer )

What about -- a filename that must be an existing file...

    [ValidateScript({Test-Path $_})][string]$smolibrary


See Also

results matching ""

    No results matching ""