PowerShell
Step 7. Variables and Data Types — Putting Values into Labeled Boxes
Level 0 — Understanding How to Operate a Computer and How It’s Structured | Difficulty ★★☆☆☆ | Estimated time: 2–3 hours
Prerequisites: Step 6 complete. Use Windows PowerShell 5.1 or PowerShell 7 on Windows. No internet connection is needed.
- What you need: a Windows PC, PowerShell.
- Safety: create example variables and arrays and query local services. No files or service settings are changed. Use a fresh practice session and follow the order below.
- Caution: let me warn you about this section’s biggest trap in advance. Double quotes and single quotes behave differently in PowerShell. Beginners lose hours over this one thing. You’ll learn it head-on in subsection 3-4 and move on.
Today “programming” begins. But don’t be intimidated. What you’ll learn today is “giving a value a name so you can pull it back out later” — the same thing, in essence, as jotting a note in daily life. Everything in this section’s chapter must be typed by hand. Reading code with your eyes alone will never make it stick. Mistakes are fine. Error messages are part of this section’s textbook too.
1. Learning Objectives
By the end of this unit, you can:
- Store values in variables and pull them back out
- Distinguish numbers, strings, and arrays, and check a data type with
GetType() - Explain the difference between double quotes (variable expansion) and single quotes (verbatim)
- Store a command’s entire result in a variable, count it, and pull out items
2. Background Knowledge — Today’s Tools and Concepts
This section’s Tools at a Glance
| Category | Details |
|---|---|
| Language/environment | Windows PowerShell 5.1 / PowerShell 7 — variables and data types |
| This section’s syntax | $variable = value (store), $variable (retrieve), @(...) (array), $( ) (embedding inside a sentence) |
| This section’s tool | GetType() (check data type) |
| Concepts you need | variables and memory, data types (number/string/array), double quotes vs single quotes |
So far, we have run commands and read their results on screen. A variable associates a name with a value for reuse, like “study topic = PowerShell.” Numbers, strings, and arrays introduce the kinds of values you can store. Use the fictional names below instead of real passwords or tokens.
2-1. Variables — Labeled Boxes
A variable is “a box with a name tag that holds a value.”
$name = "Lee"
What this one line means: “make a box with the name tag name, and put the text Lee inside it.” Later, when you call $name, the contents of the box pop out.
Reference a variable with $name. Its name is name; the dollar sign introduces the variable reference. Names are case-insensitive, so $name and $Name refer to the same variable. Do not repurpose built-in names such as $HOME, $Host, or $PID.
2-2. Inside the Computer — Memory
A variable refers to a value or object in a PowerShell session and scope. A separate new session does not automatically inherit your earlier variables. Ending a session ends its user-variable state, although a profile or script can recreate values in a new session. Clearing a variable or closing a window is not secure erasure of disk, command history, or memory.
(Note: this word “memory” comes back in great depth in Level 1. The C language and buffer overflow attacks are all memory stories. For now, just remember one line: “variables are stored in memory.”)
2-3. Data Types — The Kind of Thing in the Box
What you can do depends on what’s inside the box.
| Data type | Examples | What you can do |
|---|---|---|
| Number (integer) | 3, 42 |
arithmetic |
| Text (string) | "Lee", "hello" |
join, slice, search |
| List (array) | @("a","b","c") |
line up in order, pull out one at a time |
A “string” is the term for “characters strung together in a row.” Just think of it as text data. Anything wrapped in quotes is a string — "3" is not the number 3 but the character “3”. This difference actually causes a problem in subsection 3-3.
3. Follow Along
Before you begin. An array count, a live object reference, and a copied property value are different things. Requery when you need current state.
3-1. First Variable — Store and Retrieve
$name = "Lee"
Looks like nothing happened, right? That’s normal. Store commands are quiet. Now let’s pull it out:
$name
Lee
How to read the output: when you type just $name, PowerShell understands “show me the box’s contents” and prints them.
Why do this: these two moves — “store → retrieve” — are the basic gait of every script. With variables, you can use the same value a hundred times while managing it through one name tag, and when the value changes you fix it in just one place.
3-2. Number Variables — Becoming a Calculator
$a = 3 $b = 4 $a + $b
7
How to read the output: if 7 comes right out, it worked. We pulled the numbers out of two boxes and added them.
Why do this: a stored number can participate in later calculations. Total log lines minus ERROR lines gives non-ERROR lines; these can include WARNING lines, so do not automatically call them normal lines.
For fun, try $a * $b (multiply) and $a / $b (divide) too. PowerShell becomes a calculator on the spot.
3-3. Numbers and Text Are Different — Data Types Made Real
This time let’s cause an accident on purpose. Type:
$x = "3" $y = "4" $x + $y
Predict first: will the result be 7, or not?
Example result:
34
Not 7 but 34! Because they were wrapped in quotes, "3" and "4" are not numbers but text, and + on text means “join together.” This is the moment a data type actually changes a result.
Let’s check these boxes’ identities:
$x.GetType().Name
String
The computer itself answers: a string. Do the same with $a from before and it says Int32 (integer).
Why do this: when arithmetic surprises you, inspect both the value and its type. The example 3 is Int32, but Int64, Double, and Decimal are also numeric types. You cannot call GetType() on $null.
$a.GetType().Name (3.5).GetType().Name ([long]3000000000).GetType().Name [int]$x + [int]$y 3 + "4" "3" + 4
Int32 Double Int64 7 7 34
[int] converts to an integer. A nonnumeric string or one outside the Int32 range fails conversion. In mixed expressions the left operand influences conversion, explaining why 3 + “4” and “3” + 4 differ.
3-4. This section’s Biggest Trap — Double Quotes vs Single Quotes
Sometimes you want to use a variable inside a string. Let’s compare the two ways side by side. Type:
"Name: $name" 'Name: $name'
Output:
Name: Lee Name: $name
How to read the output: in the first line (double quotes), the variable expanded and Lee went in; in the second line (single quotes), $name came out verbatim, as literal text.
Why the difference: double quotes “inspect the contents and swap any variables for their values” (this is called variable expansion). Single quotes “treat the contents exactly as written.”
When to use which: if you want to embed a value inside a sentence, double quotes. If you want the $ symbol itself as a character, single quotes. Start with double quotes by default, and if you think “huh? the variable didn’t expand,” suspect the quotes first.
Predict first: a plain + inside a string is text, while an expression inside
$(...)is evaluated. Use${name}to mark the end of a variable name before an adjacent colon or other text."Sum: $a + $b" "Sum: $($a + $b)" "${name}: ready"Sum: 3 + 4 Sum: 7 Lee: ready
3-5. Arrays — Many Things in One Box
You want to handle several names. You could make three boxes, but one list box is better:
$list = @("apple", "banana", "kiwi")
@(...) is the sign saying “this is a list.” To pull things out, you use a number tag:
$list[0]
apple
How to read the output: the point is that apple, not banana, came out. Arrays use zero-based indexing. Number 0 is the first, number 1 is the second. Try $list[1] and $list[2] too.
Why do this: lists come up constantly in real work — lists of log files, users, servers. And when they meet next chapter’s loops, they become the powerful pattern “do the same task for every item in the list.”
Let’s also learn right now how to count a list:
$list.Count
3
.Count means “count them for me.” Similar in role to the Measure-Object you saw in Step 5.
3-6. Putting It Together — Handling a List of Names
Let’s gather what we learned today:
$members = @("Kim", "Lee", "Park")
$members.Count
"First member: $($members[0])"
3 First member: Kim
One new notation: "$($members[0])" — to put one slot of an array inside double quotes, you have to wrap it once in $( ). If you just write "$members[0]", the actual result is this:
Kim Lee Park[0]
PowerShell expands the variable $members and leaves [0] as literal text under its string-expansion rules. Put indexing, property access, or arithmetic inside $(...) to evaluate it within double quotes. The example joining array elements with spaces assumes the default $OFS behavior.
Why do this: the combination “list + count + embed in a sentence” becomes the standard pattern for auto-generating report sentences later. Example: "Files scanned: $($files.Count)".
3-7. Real-World Feel — Storing a Command’s Result in a Variable
So far we’ve written values in directly ($a = 3). But a variable’s real power shows when you store a command’s entire result:
$now = Get-Date $now
2026-09-10 09:30:00 (illustrative; display varies by locale)
What just happened: $now holds the DateTime object returned by Get-Date. The displayed time and format vary by environment. Reading $now later returns the same saved time; run Get-Date again to obtain the current time.
One step further — let’s combine it with a command from Step 5:
$services = @(Get-Service) $services.Count
310
310 illustrates the output shape, not an expected count for your machine. Values depend on the environment and query time. Query errors can leave an incomplete returned list; record the presence of errors alongside the count.
How to read the output: wrap the returned service objects in @(...) to receive an array. An ordinary command assignment can yield $null for no results, one object for one result, or an array for several results. Use @() when you want an array regardless of result count. The array’s Count is its number of elements.
$zero = @(@('one', 'two') | Select-Object -First 0)
$one = @(@('one', 'two') | Select-Object -First 1)
$many = @(@('one', 'two') | Select-Object -First 2)
$zero.Count
$one.Count
$many.Count
$one[0]
0 1 2 one
This makes zero, one, and multiple results count consistently. Read $services[0] only after confirming a nonzero Count. Ordinary command assignment captures success output; error messages do not automatically become array elements.
Why do this: this pattern — “store the result in a variable → count it → pull out what you need” — is the skeleton of every analysis script to come. Read a log file into a variable, filter only errors into another variable, judge by the count. When it meets Step 8’s loops, the picture completes.
Predict first: if you do not modify or reassign the saved
$servicesarray, its Count stays the same later. Starting or stopping a service does not automatically resize that stored array. Run Get-Service again for a current list. Holding object references is different from making a deep, immutable snapshot of every property; collect the specific values you need for later comparison.
4. Missions & Exercises
Mission — Member Introduction Script
Write code of 5 lines or fewer that satisfies the requirements below:
- Create an array
$teamholding three names (including yours — any names) - Check the count of
$team - Using a double-quoted string, print
"Our team has N members"(N comes automatically from the variable) - Print
"The team lead is OOO"(use the first slot of the array)
Exercises
Exercise 1. Explain the result of "3" + "4" and why.
Exercise 2. Explain the output difference between "Name: $name" and 'Name: $name'.
Exercise 3. You want to put one slot of an array inside double quotes. Instead of "$members[0]", how should you write it?
Exercise 4. You ran $services = Get-Service, then closed the window and reopened it. What happens to $services.Count? Why?
Answers & completion criteria · expand/collapse
5. Model Answers & Completion Criteria
Mission Model Answer
$team = @("Lee", "Kim", "Park")
$team.Count
"Our team has $($team.Count) members"
"The team lead is $($team[0])"
Expected output:
3 Our team has 3 members The team lead is Lee
How to verify: four code lines produce three output lines: 3, then Our team has 3 members, then The team lead is Lee. If Count or [0] appears as text instead of the value, check $(...).
Deeper dive: this three-element array has nonnegative indexes 0, 1, and 2. With strict mode off, $team[3] returns $null and normally displays nothing. StrictMode 3.0 treats an out-of-range index as an error. $team[-1] reads the final element. Do not generalize this into “missing slots never cause errors.”
Exercise Answers
Answer 1. The result is 34. Wrapped in quotes, they’re not numbers but strings, and + on strings is not addition but “joining.” (To add them as numbers: 3 + 4 without quotes.)
Answer 2. Double quotes expand variables — they swap the $name inside for its value (e.g., Name: Lee). Single quotes take it verbatim — they print the literal text Name: $name.
Answer 3. "$($members[0])" — you must wrap it in $( ). Written plainly, the whole array expands and [0] sticks on as text, producing weird output (see the actual test in 3-6).
Answer 4. Without additional initialization, $services is undefined in a new session. With strict mode off, it behaves as $null and $services.Count is 0. Strict mode can make undefined-variable access an error. This does not mean the PC currently has zero services. A saved script lets you rerun code; it does not automatically persist current variable state.
Completion Checklist
- [ ] I can store a value in a variable and pull it back out to print
- [ ] I can explain the difference between double and single quotes
- [ ] I can explain why
"3" + "4"is34 - [ ] I can check a variable’s data type with
GetType() - [ ] I can make an array and pull out items by number (counting from 0)
- [ ] I can store a command result in a variable and count it with
.Count - [ ] Mission: I completed the member introduction script
6. Common Pitfalls & Fixes
Wall 1. I typed a variable and nothing came out
A plain variable assignment normally emits no success output. Silence alone is not proof of success: check that the command completed and no error occurred, then read $name to verify its value. A >> continuation prompt can mean a quote or bracket is still open.
Wall 2. The variable prints literally inside a sentence
Single-quoted 'Name: $name' prints Name: $name literally. The correctly double-quoted "Name: $name" in this example prints Name: Lee. If the variable did not expand even though you used double quotes, inspect the actual quotes and escape characters you typed.
Wall 3. Numbers joined instead of adding
Two strings concatenate to 34 in this example. Store numeric values or explicitly convert a suitable numeric string with a cast such as [int] when arithmetic is intended. Int32 is not the only numeric type; Int64, Double, and Decimal are also numeric.
Wall 4. The wrong thing comes out of an array
Symptom: wanted the first item but got the second, or called past the end and got nothing.
Cause: you forgot numbering starts at 0. The first is [0]; the end of a three-item list is [2].
Fix: memorize “number = which one − 1.” And build the habit of checking the list length with $list.Count first.
Wall 5. I made a variable and it vanished a while later
Check that you continued in the same practice session. Separate sessions, function or script scopes, reassignment, and removal can explain a missing value. A visually identical window does not guarantee the same PowerShell session or scope. Rerun the original assignment and inspect the value.
7. Summary
This section’s Core Table
| Concept | Analogy | PowerShell notation |
|---|---|---|
| Variable | a labeled box (stored in memory) | $name = "Lee" |
| String | text data | "hello" (example string literal) |
| Integer | number data | 3 (no quotes) |
| Array | a list box with number tags | @("a","b","c"), starting at [0] |
This section’s Trap Card
| Situation | Result | Lesson |
|---|---|---|
"$name" (double quotes) |
variable expands | when embedding a value |
'$name' (single quotes) |
literal text | when you want the $ symbol itself |
"3" + "4" |
34 |
quotes = string |
3 + 4 |
7 |
no quotes = number |
"$list[0]" |
weird output | array slots go in $($list[0]) |
Instincts That Matter More Than Commands
“Always be aware of what kind of thing is in the box.” “I thought it was a string but it was a number (or vice versa)” is a bug that sometimes becomes the seed of a real security vulnerability. When in doubt, check identity with GetType() — that habit is this section’s real takeaway.
Two nice-to-knows: code that “takes user-input values into variables and embeds them straight into commands” is a staple ingredient of injection attacks — you’ll feel the reason for the iron rule “never blindly trust values from outside” when you carry out such attacks yourself in Level 2. And in real work, people use names like $loginFailCount instead of $a — “names that tell you what they are when read.” Code whose purpose is visible from names alone reads without a manual.
Once every box is checked, Step 7 is complete.
Practice verification record
Historical record. The dated record below describes the earlier lesson version. The current instructions include subsequent editorial corrections; that record does not certify every revised example.
On 2026-09-10, all executable blocks were run in order using Windows PowerShell 5.1.26100.9444 and PowerShell 7.6.5. Checks covered numeric and string types, casts, quote expansion, arrays with zero/one/multiple elements, stored service-array counts, and the three-line mission output. Separate isolated sessions distinguished undefined-variable behavior and strict-mode index errors. No services were started or stopped and no profiles were changed.
ONE STEP FURTHER
Finished this lesson?
Check the completion criteria, then mark your progress.