PowerShell Variables
A variable is a named box that holds a value. You store a value in a variable once and use its name whenever you need that value again.
Store a value in a variable
Use the equals sign to store a value. Then type the variable name to print the value.
$name = "Ana"
$nameChange the stored value
Assign a new value to the same name. The old value is replaced.
$city = "Seattle"
$city = "Portland"
$cityFill a value into text
Double quotes replace a variable name with its value. This is called interpolation.
$name = "Ana"
$age = 31
"$name is $age years old"Example
$name = "Ana"
$city = "Seattle"
$greeting = "Hello, $name"
$greeting
"$name lives in $city"Key points
- Variable: a named box that holds a value.
- Name: a variable name starts with a dollar sign.
- Assignment: use the equals sign to store a value in a variable.
- Change: assign a new value to change what a variable holds.
- Interpolation: double quotes fill in a variable name with its value.
In this example, the first two lines store a name and a city. The third line builds a greeting with the name filled in. The last two lines print the greeting and a sentence about where Ana lives.
Note
single quotes do not fill in variable names. They keep the text exactly as written.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does $name print after these two lines: $name = "Ana" and $name = "Lee"?