Passing an argument from command line to PowerShell script

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

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:

  1. 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):

    powershell
    param(
    [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:

    arduino
    PowerShell.exe -ExecutionPolicy Bypass -File script.ps1 "value1" "value2"

    Replace "value1" and "value2" with the actual values you want to pass as arguments.

  2. 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):

    powershell
    param(
    [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:

    arduino
    PowerShell.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.