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 that 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

param([type]$p1 = , [type]$p2 = , ...)

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 the 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:

[Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]

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.

param (
        [string]$p1,
	[string]$p2,
	[string]$p3

 )

Write-Host "The Concatenated String is $p1 $p2 $p3"

Execution the PowerShell Script from Command Line Parameters

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

 .\example.ps1 Hello World !!!
 .\example.ps1 abc pqr xyz

# Output
# The Concatenated String is Hello World !!!
# The Concatenated String is abc pqr xyz

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

powershell.exe -File "C:\example.ps1" arg1 arg2 arg3

# OR

powershell.exe -File "C:\example.ps1" Hello World !!!

Example 2:

PowerShell Command Line Parameter with Attributes

param (
    [string]$server = "http://defaultserver",
    [Parameter(Mandatory=$true)][string]$username,
    [string]$password = $( Read-Host "Input password, please" )
 )

$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.

Leave a Reply

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

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like