Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell, call script with parameter without a value, like a script with options

Tags:

powershell

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.

like image 891
Christian Avatar asked Jan 31 '14 12:01

Christian


People also ask

How do I call a PowerShell script with parameters?

You can run scripts with parameters in any context by simply specifying them while running the PowerShell executable like powershell.exe -Parameter 'Foo' -Parameter2 'Bar' . Once you open cmd.exe, you can execute a PowerShell script like below.

How do you make parameters mandatory in PowerShell?

To make a parameter mandatory add a "Mandatory=$true" to the parameter description. To make a parameter optional just leave the "Mandatory" statement out. Make sure the "param" statement is the first one (except for comments and blank lines) in either the script or the function.

What is optional parameter in PowerShell?

By default, PowerShell parameters are optional. When a user does not submit arguments to a parameter, PowerShell uses its default value. If no default value exists, the parameter value is $null. This is not always desired. There are situations when default values simply do not make sense.

Which of these are valid ways of providing multiple parameters to a command?

To pass multiple parameters you must use the command line syntax that includes the names of the parameters.


1 Answers

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)

like image 185
RB. Avatar answered Oct 22 '22 20:10

RB.