PowerShell command line arguments let you pass input directly to a script or command when you run it, enabling dynamic behavior without editing the script. You need PowerShell installed (it comes pre-installed on Windows 10/11 and modern Windows Server versions) and basic familiarity with writing or using PowerShell scripts.

What You'll Need

  • Windows 10 or later (or Windows Server 2016+) with PowerShell 5.1+ or PowerShell Core 6+ (PowerShell 7.x is recommended for cross-platform use)
  • A text editor (e.g., Notepad, VS Code) to create or edit scripts
  • Basic understanding of PowerShell syntax, including functions and parameters

Step-by-Step

  1. Open PowerShell. Press Windows + X and select Windows PowerShell or PowerShell (or search for "PowerShell" in the Start menu).
  2. Create a new script file. In Notepad or VS Code, type the following minimal script that accepts two arguments: $name and $repeatCount. Save it as greet.ps1 in a known folder (e.g., C:\Scripts):
    param(
        [Parameter(Mandatory=$true)]
        [string]$name,
        
        [Parameter(Mandatory=$false)]
        [int]$repeatCount = 1
    )
    
    for ($i = 0; $i -lt $repeatCount; $i++) {
        Write-Host "Hello, $name!"
    }
    Note: The param() block defines the arguments. Mandatory=$true ensures the script fails if $name is omitted.
  3. Set execution policy to allow script running (if needed). By default, Windows restricts script execution. Run this command in PowerShell (as Administrator if you see an error):
    Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
    This allows locally created scripts to run without a digital signature.
  4. Call the script with arguments. In PowerShell, navigate to the script folder and run:
    cd C:\Scripts
    ./greet.ps1 -name "Alice" -repeatCount 3
    This outputs:
    Hello, Alice!
    Hello, Alice!
    Hello, Alice!
  5. Use positional arguments (optional). PowerShell supports positional parameters if you omit the parameter name and rely on order. Modify the script’s param() block to include [Position(0)] and [Position(1)] attributes:
    param(
        [Parameter(Position=0, Mandatory=$true)]
        [string]$name,
        
        [Parameter(Position=1, Mandatory=$false)]
        [int]$repeatCount = 1
    )
    Now you can run:
    ./greet.ps1 "Bob" 2
    This works because "Bob" maps to position 0 ($name) and 2 maps to position 1 ($repeatCount).
  6. Handle switches (boolean flags). Add a switch parameter to enable optional behavior. Update the script:
    param(
        [Parameter(Mandatory=$true)]
        [string]$name,
        
        [Parameter(Mandatory=$false)]
        [int]$repeatCount = 1,
        
        [switch]$upperCase
    )
    
    $message = "Hello, $name!"
    if ($upperCase) {
        $message = $message.ToUpper()
    }
    
    for ($i = 0; $i -lt $repeatCount; $i++) {
        Write-Host $message
    }
    Run with:
    ./greet.ps1 -name "Charlie" -upperCase
    Output: HELLO, CHARLIE! (repeated once, as $repeatCount defaults to 1).

Common Mistakes

  • Missing quotes around arguments with spaces. Running ./greet.ps1 -name Alice Smith fails because PowerShell treats "Alice Smith" as two separate arguments. Always quote strings: -name "Alice Smith".
  • Incorrect parameter binding. Using -name=Bob instead of -name Bob causes an error in PowerShell. Command-line parameters use spaces, not equals signs (unlike some other shells).
  • Forgetting Mandatory=$true for required inputs. Without it, omitting $name silently uses an empty string, leading to unexpected output like "Hello, !".
  • Execution policy blocking the script. If you see "scripts are disabled on this system", you must adjust the policy as described in Step 3.
  • Mixing positional and named arguments incorrectly. If you specify ./greet.ps1 "Alice" -repeatCount 2 but the script expects positional order, ensure positions align with parameter attributes.

Tips

  • Use [ValidateNotNullOrEmpty()] or [ValidateRange()] inside param() to enforce input rules. Example: [ValidateRange(1, 10)][int]$repeatCount prevents values outside 1–10.
  • Test argument parsing interactively first. In PowerShell, type param($x, $y) then press Enter, followed by $x = 5; $y = 10 to simulate argument assignment before writing a full script.
  • Use $PSBoundParameters to debug which arguments were provided. Add Write-Host "Bound params: $($PSBoundParameters -join ', ')" inside your script to see runtime values.
  • For complex scripts, define default values in param() to avoid errors when arguments are omitted (e.g., [int]$count = 1).
  • Use -ErrorAction Stop in your script’s cmdlets to catch argument-related errors and handle them gracefully with try/catch blocks.

Troubleshooting

If your script fails to accept arguments:

  1. Check PowerShell version. Run $PSVersionTable.PSVersion. If it’s below 5.1, update PowerShell (download PowerShell 7.x from Microsoft’s official site).
  2. Verify script file encoding. Save scripts as UTF-8 (without BOM) in your editor. Corrupted encoding can cause silent parsing errors.
  3. Review parameter definitions. Ensure param() is the first non-comment line in the script (after #requires if used). Any code before param() prevents argument binding.
  4. Test with a simple script. Create test.ps1 with just param($a) Write-Host "Got: $a" and run ./test.ps1 hello. If this fails, the issue is environment-wide (e.g., execution policy).
  5. Check for hidden characters. Copy-pasting code from websites can introduce invisible characters. Retype the command manually or use a clean editor.
  6. Review error messages carefully. PowerShell’s error output (e.g., "Cannot validate argument on parameter 'name'") often pinpoints the exact issue, such as type mismatch or validation failure.

Frequently Asked Questions

Can I pass arrays as command line arguments?

Yes. Use comma-separated values with quotes: ./script.ps1 -items "a,b,c" and convert inside the script: $items = $items -split ','. Alternatively, use PowerShell’s array syntax: ./script.ps1 -items @("a", "b", "c") (requires PowerShell 3+).

Do I need to quote empty strings or null values?

For mandatory string parameters, omitting the argument fails. For optional ones, use -name "" to pass an empty string, or omit the parameter entirely to use the default.

Can I use command line arguments with compiled .exe files in PowerShell?

Yes. PowerShell passes arguments to external executables exactly as typed: myapp.exe arg1 arg2. For .NET executables, arguments go to Main(string[] args).

What happens if I pass more arguments than a script expects?

PowerShell ignores extra arguments and displays a warning: "The term 'extra' is not recognized..." unless you use $args (the automatic variable for unbound arguments) in your script.

How do I handle arguments that include special characters like & or |?

Always wrap such strings in double quotes. For example: -path "C:\Data & Reports". Single quotes work too, but double quotes allow variable expansion.

Is there a limit to how many arguments I can pass?

PowerShell itself supports long command lines, but Windows has a 8191-character limit for command-line strings. Split very long inputs into a file and use Get-Content instead.