36

Is it possible to call a PowerShell script with options? Like a parameter without a value.

For instance I currently use:

param (
    $lastmonth=0
);

in the script. Now I can use the call

script.ps1 -lastmonth 1

or

script.ps1 

and use $lastmonth for controlling the flow.

But I'd like to have the calls like

script.ps1 -lastmonth

and

script.ps1

and control the flow depending on whether -lastmonth was given, or not.

2 Answers 2

81

Set the type of your parameter to [switch], e.g.

param (
    [switch]$lastmonth
);

EDIT: Note that the variable will be a boolean. You can test it like:

if ($lastMonth) {
    Write-Host "lastMonth is set."
}
else {
    Write-Host "lastMonth is not set."
}

(thanks Chris)

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

3 Comments

... and then it's a boolean variable.
@Chris Lol, yep, should probably have mentioned that! I'll update my answer :)
It seems you have to explicitly use $lastMonth.IsPresent for unary conditions, as it is not a true boolean. if ($lastMonth) works $lastMonth?x:y does not, but $lastMonth.IsPresent?x:y does. PS 7.3.9
3

This is called a switch parameter. Checkout out the official documentation @ Microsoft Docs.

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.