Menu
CoddyTech

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 icon

Challenge

Beginner

Track the stock of one product in a shop.

  1. Create a variable $product with the text Laptop and a variable $stock with the number 12.
  2. Print Product: followed by the product, then Stock: followed by the stock.
  3. Three laptops are sold: subtract 3 from $stock and store the result in $stock.
  4. Print the stock line again.

Your script prints:

Product: Laptop
Stock: 12
Stock: 9

Try it yourself

# 1. Create $product and $stock

# 2. Print the product and the stock

# 3. Sell three laptops

# 4. Print the stock again
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in PowerShell Basics