Using variables in a PowerShell script stores values you can reuse and change in one place, making scripts more flexible and readable. Windows 11’s PowerShell handles variables simply, forming a core building block of any script beyond the most basic.
The Command
$name = "Alice"; Write-Output "Hello, $name"
What It Does
In PowerShell, variables begin with a dollar sign, so `$name = “Alice”` stores the text Alice in the variable name. When you include `$name` inside a double-quoted string, PowerShell substitutes its value, so the output YYGACOR Login becomes Hello, Alice. Variables let you store and reuse values, referring to them by name throughout a script.
When You’d Use This
This is fundamental to writing flexible scripts, since variables let you store values, reuse them, and change them in one place rather than repeating literals throughout. Any script beyond the most basic uses variables to hold filenames, counts, command results, or user input, making them a core building block for automation that adapts to different values.
Useful Variations
Variables can hold numbers, text, lists, or command results, such as `$files = Get-ChildItem` storing a file list. To include a variable’s value in output, double-quoted strings expand it while single-quoted strings do not. You can change a variable’s value at any point, and later references use the new value.
If It Doesn’t Work
If a variable’s name appears literally in output instead of its value, you likely used single quotes, which do not expand variables, so switch to double quotes where you want substitution. If a variable seems empty, confirm it was assigned before use. Choosing clear, descriptive names avoids confusion and makes scripts much easier to read and maintain as they grow more complex.
Good to Know
Double quotes allow variable substitution inside strings while single quotes treat the text literally, which is a common source of confusion when a variable name appears verbatim instead of its value. Choosing clear, descriptive variable names makes scripts much easier to read and maintain, especially as they grow more complex.
Putting It Together
Once you have run it once or twice, this becomes second nature. As part of working with output and building simple automation, this command is a building block you will reuse constantly. As you combine it with the other scripting basics here, small one-off commands grow into reusable scripts that save real time on repetitive work. Like anything in the terminal, the real value comes from trying it on your own system and adapting the variations above to what you actually need, so it is worth experimenting with in a safe, low-stakes situation before relying on it in a script or during troubleshooting. Keeping a note of the commands you find most useful, along with the variations that fit your workflow, turns scattered one-off tricks into a personal reference you can draw on whenever a similar task comes up again.