How to Create Variable in PowerShell: Simple Guide
In PowerShell, you create a variable by using the
$ sign followed by the variable name, like $myVar. You assign a value using the = operator, for example, $myVar = 10 creates a variable named $myVar with the value 10.Syntax
To create a variable in PowerShell, start with the $ symbol, then write the variable name, followed by an equals sign =, and then the value you want to assign.
- $: Indicates a variable.
- VariableName: The name you choose for your variable.
- =: Assignment operator.
- Value: The data you want to store (number, text, object, etc.).
powershell
$VariableName = Value
Example
This example shows how to create a variable named $greeting and assign it a text value. Then it prints the value to the screen.
powershell
$greeting = "Hello, friend!"
Write-Output $greetingOutput
Hello, friend!
Common Pitfalls
Some common mistakes when creating variables in PowerShell include:
- Forgetting the
$sign before the variable name. - Using spaces in variable names (use underscores or camelCase instead).
- Not using quotes for text values.
- Trying to assign a value without the
=operator.
Here is a wrong and right way example:
powershell
# Wrong way (missing $ and quotes)
$name = John
# Right way
$name = "John"Quick Reference
| Concept | Example | Notes |
|---|---|---|
| Create variable | $var = 5 | Stores number 5 in $var |
| Text value | $text = "Hi" | Use quotes for strings |
| Use variable | Write-Output $var | Prints variable value |
| Variable name rules | No spaces, start with letter | Use letters, numbers, underscores |
| Change value | $var = 10 | Variables can be reassigned |
Key Takeaways
Always start variable names with a $ sign in PowerShell.
Use the = operator to assign values to variables.
Put quotes around text values to avoid errors.
Variable names cannot contain spaces; use underscores or camelCase.
You can change a variable's value anytime by assigning a new value.