How to Pass an Argument to a PowerShell Script

Rohan Timalsina Feb 02, 2024
  1. Use param to Pass an Argument to a PowerShell Script
  2. Use args to Pass an Argument to a PowerShell Script
How to Pass an Argument to a PowerShell Script

The PowerShell script is a collection of commands saved in a .ps1 extension file.

PowerShell executes those commands in sequence. This tutorial will introduce different methods to pass arguments to a PowerShell script.

Use param to Pass an Argument to a PowerShell Script

We can define arguments using the param statement. It also allows us to use the default values.

We have created a myscript.ps1 script file which contains:

param($name, $address = "USA", $age)
Write-Host "Name: $name"
Write-Host "Address: $address"
Write-Host "Age: $age"

Here, the variable $address has a default value. And the default value will be used if the user does not provide any value.

Also, we can specify the variable to set a value.

./myscript.ps1 -name "Rohan" -age "20"

Output:

Name: Rohan
Address: USA
Age: 20

Use args to Pass an Argument to a PowerShell Script

Another method to pass an argument to a PowerShell script is through the $args[] array. We do not get to put the argument name in this method.

We have written a new script in the myscript2.ps1 file.

Write-Host Name: $args[0]
Write-Host Address: $args[1]
Write-Host Age: $args[2]

We do not have much control over input as they are used in a sequence order in the args[] array. For example, the first value is stored at [0], second at [1], third at [2], and so on.

./myscript2.ps1 "Rohan" "USA" "20"

Output:

Name: Rohan
Address: USA
Age: 20
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 Script