How to Accessing the $args Array in PowerShell

Rohan Timalsina Feb 02, 2024
  1. Use $args Array in PowerShell
  2. Use $args[] in PowerShell
How to Accessing the $args Array in PowerShell

$args is an array, so you can pass multiple values and access them in a PowerShell script or function. This tutorial will introduce the $args array in PowerShell.

Use $args Array in PowerShell

The $args stores the values for undeclared parameters passed to a script or function and is one of the automatic variables created and maintained by PowerShell.

For example, this function takes arguments from the input.

function test_args() {
    Write-Host "First argument is $($args[0])"
    Write-Host "Second argument is $($args[1])"
}

The subexpression operator $() allows you to use an expression within another expression. It converts the result to a string expression inside the double quotes " ".

If you call the function test_args and pass the arguments, it returns the following output.

test_args Hello World

Output:

First argument is Hello
Second argument is World

The arguments are passed in the ascending order starting from zero in the args[] array. For example, the first value is stored at [0], second at [1], third at [2], and so on.

Use $args[] in PowerShell

You can also refer to specific arguments by their position using $args[]. We have created a myscript.ps1 script that contains the commands below.

$name=$args[0]
$age=$args[1]
Write-Host "My name is $name."
Write-Host "I am $age years old."

Call the script and pass the arguments.

.\myscript.ps1 John 21

Output:

My name is John.
I am 21 years old.
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Array