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
- Open PowerShell. Press Windows + X and select Windows PowerShell or PowerShell (or search for "PowerShell" in the Start menu).
- Create a new script file. In Notepad or VS Code, type the following minimal script that accepts two arguments:
$nameand$repeatCount. Save it asgreet.ps1in a known folder (e.g.,C:\Scripts):
Note: Theparam( [Parameter(Mandatory=$true)] [string]$name, [Parameter(Mandatory=$false)] [int]$repeatCount = 1 ) for ($i = 0; $i -lt $repeatCount; $i++) { Write-Host "Hello, $name!" }param()block defines the arguments.Mandatory=$trueensures the script fails if$nameis omitted. - 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):
This allows locally created scripts to run without a digital signature.Set-ExecutionPolicy RemoteSigned -Scope CurrentUser - Call the script with arguments. In PowerShell, navigate to the script folder and run:
This outputs:cd C:\Scripts ./greet.ps1 -name "Alice" -repeatCount 3Hello, Alice! Hello, Alice! Hello, Alice!
- 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:
Now you can run:param( [Parameter(Position=0, Mandatory=$true)] [string]$name, [Parameter(Position=1, Mandatory=$false)] [int]$repeatCount = 1 )
This works because "Bob" maps to position 0 (./greet.ps1 "Bob" 2$name) and 2 maps to position 1 ($repeatCount). - Handle switches (boolean flags). Add a switch parameter to enable optional behavior. Update the script:
Run with: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 }
Output:./greet.ps1 -name "Charlie" -upperCaseHELLO, CHARLIE!(repeated once, as$repeatCountdefaults to 1).
Common Mistakes
- Missing quotes around arguments with spaces. Running
./greet.ps1 -name Alice Smithfails because PowerShell treats "Alice Smith" as two separate arguments. Always quote strings:-name "Alice Smith". - Incorrect parameter binding. Using
-name=Bobinstead of-name Bobcauses an error in PowerShell. Command-line parameters use spaces, not equals signs (unlike some other shells). - Forgetting
Mandatory=$truefor required inputs. Without it, omitting$namesilently 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 2but the script expects positional order, ensure positions align with parameter attributes.
Tips
- Use
[ValidateNotNullOrEmpty()]or[ValidateRange()]insideparam()to enforce input rules. Example:[ValidateRange(1, 10)][int]$repeatCountprevents values outside 1–10. - Test argument parsing interactively first. In PowerShell, type
param($x, $y)then press Enter, followed by$x = 5; $y = 10to simulate argument assignment before writing a full script. - Use
$PSBoundParametersto debug which arguments were provided. AddWrite-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 Stopin your script’s cmdlets to catch argument-related errors and handle them gracefully withtry/catchblocks.
Troubleshooting
If your script fails to accept arguments:
- Check PowerShell version. Run
$PSVersionTable.PSVersion. If it’s below 5.1, update PowerShell (download PowerShell 7.x from Microsoft’s official site). - Verify script file encoding. Save scripts as UTF-8 (without BOM) in your editor. Corrupted encoding can cause silent parsing errors.
- Review parameter definitions. Ensure
param()is the first non-comment line in the script (after#requiresif used). Any code beforeparam()prevents argument binding. - Test with a simple script. Create
test.ps1with justparam($a) Write-Host "Got: $a"and run./test.ps1 hello. If this fails, the issue is environment-wide (e.g., execution policy). - Check for hidden characters. Copy-pasting code from websites can introduce invisible characters. Retype the command manually or use a clean editor.
- 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 useGet-Content instead.