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.
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.
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.
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.
To pass multiple parameters you must use the command line syntax that includes the names of the parameters.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With