Handling Command-Line Arguments in PowerShell

Command-line arguments allow us to pass information to our scripts dynamically, making them more flexible and versatile. In this blog post, we’ll explore handling command-line arguments in PowerShell.

Handling Command-Line Arguments in PowerShell Using Args

When we execute a PowerShell script from the command line, we can pass arguments after the script’s name. For example:

powershell.exe Alkane.ps1 "Alkane" "Solutions"

In this example, we’re executing the script “Alkane.ps1” and passing “Alkane” and “Solutions” as command-line arguments. These arguments can be used to customise the behaviour of our script without modifying the script itself.

In this example, command-line arguments are accessed using the special variable $args :

$arg1 = $args[0]
$arg2 = $args[1]
Write-Host "Argument 1: $arg1"
Write-Host "Argument 2: $arg2"

In the code above, we’re accessing the first two command-line arguments using $args[0] and $args[1] , respectively. We then display these arguments using the Write-Host cmdlet.

We can verify the number of command-line arguments by getting the Count property of the $args variable:

if ($args.Count -lt 2) {
Write-Host "Please provide at least two arguments."
} else {
$arg1 = $args[0]
$arg2 = $args[1]
#Script logic here
Write-Host "Argument 1: $arg1"
Write-Host "Argument 2: $arg2"
}

Handling Command-Line Arguments in PowerShell Using Named Parameters

We can also pass command-line arguments in PowerShell using named parameters. For example:

powershell.exe Alkane.ps1 -First "Alkane" -Second "Solutions"

In this example, we’re executing the script “Alkane.ps1” and passing “Alkane” via a parameter called “First”, and “Solutions” via a parameter called “Second”.

To access the parameter values, we must handle them in a param section at the very beginning of our script like so:

param (
$first,
$second
)
Write-Host "First 1: $first" 
Write-Host "Second 2: $second"

By incorporating arguments in our PowerShell scripts, we can create scripts that adapt to various scenarios without the need for constant script modifications.