- 1 year ago
Passing an argument from command line to PowerShell script
To pass an argument from the command line to a PowerShell script, you can use the $args
variable or explicitly define parameters in the script. Here are two approaches:
Using the
$args
variable:
In your PowerShell script, you can access command line arguments through the automatic variable$args
. It contains an array of the arguments passed to the script.Example PowerShell script (
script.ps1
):powershellparam(
[string]$arg1,
[string]$arg2
)
Write-Host "Argument 1: $arg1"
Write-Host "Argument 2: $arg2"
From the command line, you can run the script and pass the arguments like this:
arduinoPowerShell.exe -ExecutionPolicy Bypass -File script.ps1 "value1" "value2"
Replace
"value1"
and"value2"
with the actual values you want to pass as arguments.Using explicit parameters:
You can also explicitly define parameters in your PowerShell script, allowing you to specify their names and data types.Example PowerShell script (
script.ps1
):powershellparam(
[Parameter(Mandatory=$true)]
[string]$arg1,
[Parameter(Mandatory=$true)]
[string]$arg2
)
Write-Host "Argument 1: $arg1"
Write-Host "Argument 2: $arg2"
From the command line, you can pass the arguments using the parameter names:
arduinoPowerShell.exe -ExecutionPolicy Bypass -File script.ps1 -arg1 "value1" -arg2 "value2"
Replace
"value1"
and"value2"
with the actual values you want to pass as arguments.
In both approaches, the PowerShell script can access the command line arguments and use them as needed. You can modify the script to handle additional parameters or perform different actions based on the passed arguments.