Pass Command Line Arguments in PowerShell Script

PowerShell provides an efficient way to pass command line arguments by using parameters inside a PowerShell script. PowerShell comes up with a param statement which can be used at the beginning of the script. The param statement must be the first executable line in the script with the only comment or empty lines preceding it.

Syntax of Param Statement

The types can be anything like String, Int etc and you also have the option to make the parameters mandatory. Let us take a look at below examples to have a clear idea of command line arguments in PowerShell script.

Parameter Attributes in PowerShell
The params statement block can also optionally define parameter attributes:

These affect the function parameters as follows:

Mandatory – Whether the parameter is mandatory or optional (the default)

ValueFromPipeline – Accept values via the pipeline, of the same type expected by the parameter or that can be converted to the type that the parameter is expecting.

ValueFromPipelineByPropertyName – Accept values via the pipeline of the same type expected by the parameter and which also must have the same name as the parameter accepting pipeline input.

How to Pass Command Line Arguments in PowerShell Script

Example 1:

This is a simple example where we have declared the param p1, p2, and p3 and we are just concatenating this parameter in the PowerShell script.

Execution the PowerShell Script from Command Line Parameters

We can save the above script as example.ps1 and to execute this script we need to open PowerShell and type the file name with the parameters.

If you are using the command line then to execute the PowerShell script you could use below format.

Example 2:

PowerShell Command Line Parameter with Attributes

$server – Gets default value from the script if nothing is passed.

$username– We have made it mandatory and if it is not passed on the command line the script will stop execution

$password- Not mandatory can be passed or omitted.

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.