If you’re working with PowerShell regularly—whether for system administration, DevOps automation, or cloud management—you’ve likely encountered a situation where you need to make your scripts more dynamic. Instead of hardcoding values, you can pass variables to a PowerShell script at runtime.
In this detailed tutorial, you’ll learn multiple ways to pass variables to PowerShell scripts, from command-line arguments to environment variables, with clear examples and best practices.
Why We Need to Pass Variables to a PowerShell Script
Passing variables to a script allows you to reuse the same code for different scenarios. For example, you might have a script that creates a new user account. Instead of editing the script each time to change the username, you can simply pass the username as a parameter.
It also allows you to integrate PowerShell with CI/CD pipelines, scheduled tasks, and remote servers seamlessly.
Defining Parameters Inside a PowerShell Script
Before you can pass variables into a PowerShell script, you need to define parameters that will receive those values. Parameters are declared at the top of your script using the param() block. This tells PowerShell what inputs the script expects and how to handle them.
Here’s an example PowerShell script named Get-UserInfo.ps1:
param(
[string]$UserName,
[int]$UserAge
)
Write-Host "User Name: $UserName"
Write-Host "User Age: $UserAge"In this script, $UserName and $UserAge act as placeholders for the values you’ll pass when running the script. The [string] and [int] types ensure that the inputs are treated as text and numbers, respectively. Defining parameters like this makes your code cleaner, safer, and easier to maintain.
Check out List All Environment Variables in PowerShell
Passing Variables from the PowerShell Command Line
Once parameters are defined, you can pass variables directly from the PowerShell console when running the script. This is the most common and straightforward method.
Here is an example.
.\Get-UserInfo.ps1 -UserName "John" -UserAge 30When executed, the script displays:
User Name: John
User Age: 30This method is explicit and easy to read. You can pass parameters in any order as long as you specify the parameter names. It’s ideal for scripts that need to run interactively or be executed by other administrators.
Using Positional Parameters for Simplicity
PowerShell also allows you to pass parameters without explicitly naming them, as long as you maintain the correct order. These are called positional parameters.
.\Get-UserInfo.ps1 "John" 30This works because the parameters are defined in the same order inside the param() block. While this approach saves a few keystrokes, it’s best reserved for short, simple scripts. In production environments, named parameters are preferred for clarity and maintainability.
Passing Variables from Another PowerShell Script
In many automation workflows, one script calls another. PowerShell makes it easy to pass variables between scripts, allowing you to build modular and reusable code.
Here’s an example:
Parent Script (Run-Script.ps1):
$User = "Mary"
$Age = 28
.\Get-UserInfo.ps1 -UserName $User -UserAge $AgeThis approach is useful when you have a master script orchestrating multiple smaller scripts. It allows you to centralize logic while keeping each script focused on a specific task.
Read Create an HTML Table from Variables in PowerShell
Passing Variables via the Command Line from CMD or Other Tools
If you’re running PowerShell from Command Prompt, Task Scheduler, or another automation tool, you can use the -Command parameter to pass variables.
powershell -Command "& { .\Get-UserInfo.ps1 -UserName 'Alex' -UserAge 25 }"This method is particularly valuable when integrating PowerShell with batch files, CI/CD pipelines, or third-party automation systems. It ensures your scripts can run seamlessly in different environments.
Using Environment Variables to Pass Data
Environment variables are another flexible way to pass data into a PowerShell script. They’re especially useful in cloud or containerized environments where values may change dynamically.
Example:
$env:UserName = "Chris"
$env:UserAge = "35"
.\Get-UserInfo.ps1 -UserName $env:UserName -UserAge $env:UserAgeBy using environment variables, you can easily manage configuration values without altering your script. This is ideal for automation pipelines or when working with secure credentials.
Check out How to Prompt for Variable in PowerShell?
Making Parameters Mandatory and Adding Help Messages
To make your PowerShell scripts more user-friendly, you can define mandatory parameters and include help messages. This ensures that users provide the required inputs before the script runs.
param(
[Parameter(Mandatory = $true, HelpMessage = "Enter the user's name.")]
[string]$UserName,
[Parameter(Mandatory = $true, HelpMessage = "Enter the user's age.")]
[int]$UserAge
)
Write-Host "Processing user: $UserName, Age: $UserAge"When you run this script without providing parameters, PowerShell will prompt you to enter them interactively. This feature improves script reliability and user experience.
Check out Trim the Last 4 Characters from a Variable in PowerShell
Passing Complex Data: Arrays and Objects
PowerShell supports passing more than just strings and numbers—you can also pass arrays and even complex objects. This is powerful when dealing with lists or structured data.
For example, to pass an array of names:
param(
[string[]]$Names
)
foreach ($name in $Names) {
Write-Host "Processing user: $name"
}Run it like this:
.\Get-UserInfo.ps1 -Names "Alice","Bob","Charlie"This approach is perfect for batch operations, such as processing multiple files, users, or servers in a single script run.
Check out PowerShell New-Variable Cmdlet
Troubleshooting Common Issues
Here are some common errors that you might receive while sending parameters in your PowerShell script.
| Problem | Likely Cause | Recommended Solution |
|---|---|---|
| Script doesn’t accept parameters | Missing param() block | Add a properly defined parameter block |
| Values not passing correctly | Incorrect quoting or syntax | Use double quotes around string values |
| Script fails to run | Execution policy restrictions | Run Set-ExecutionPolicy RemoteSigned as Administrator |
Best Practices for Passing Variables in PowerShell
From my experience, now let me share with a few best practices for passing variables in PowerShell.
- Always define parameter types such as
[string],[int], or[bool]. - Prefer named parameters instead of positional ones for clarity.
- Include validation attributes and help messages to guide users.
- Keep your scripts modular—use one script to call another when needed.
- Follow PowerShell style and naming conventions for consistency and readability.
Conclusion
In this tutorial, I explained how to pass variables to a PowerShell script using various examples. It transforms static scripts into dynamic tools that can adapt to any situation—whether you’re managing servers, automating deployments, or configuring cloud environments.
By defining parameters, using environment variables, and following best practices, you can write PowerShell scripts that are clean, flexible, and easy to maintain. Start applying these techniques today, and you’ll quickly see how much more powerful and efficient your automation workflows become.
You may also like:
Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.