Variables
Part of the PowerShell Basics section of Coddy's PowerShell journey. Lesson 6 of 28.
A variable stores a value under a name. In PowerShell every variable name starts with $, and = stores a value in it:
$city = "Oslo"
$visitors = 250
Write-Output $city
Write-Output ("Visitors: " + $visitors)Oslo
Visitors: 250+ joins text with a value. Wrap the whole expression in parentheses when you pass it to Write-Output.
Storing a new value replaces the old one, and the right side can use the variable itself: $visitors = $visitors + 10 makes it 260.
Variable names are not case-sensitive: $City and $city are the same variable. A variable that was never given a value holds $null and prints nothing.
Challenge
BeginnerTrack the stock of one product in a shop.
- Create a variable
$productwith the textLaptopand a variable$stockwith the number12. - Print
Product:followed by the product, thenStock:followed by the stock. - Three laptops are sold: subtract
3from$stockand store the result in$stock. - Print the stock line again.
Your script prints:
Product: Laptop
Stock: 12
Stock: 9Try it yourself
# 1. Create $product and $stock
# 2. Print the product and the stock
# 3. Sell three laptops
# 4. Print the stock again
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PowerShell Basics
5Project: Password Checker
Project OverviewLength Check