Powershell Variables And Scope
Variables are the fundamental tool of any programming language, and PowerShell is no exception.
We can use variables to store numbers, strings, objects, arrays, hashtables... and what truly makes PowerShell variables powerful is its **scope mechanism**. Understanding scope allows you to write more stable, better-structured scripts and avoid variable conflicts or accidental overwrites.
This section will give you a comprehensive understanding of how variables are used in PowerShell, their data types, scope rules, and best practices.
* * *
## 1. Variable Basics
### Defining Variables
In PowerShell, variables start with a dollar sign (`$`) followed by the variable name.
$greeting = "Hello, PowerShell"
$number = 100
Variable assignment does not require prior type declaration; PowerShell will automatically infer the data type.
### Reading Variables
Simply reference the variable to read its value:
Write-Output $greeting
You can also insert it into strings:
Write-Output "Prompt message: $greeting"
If the string uses single quotes, the variable will not be parsed:
Write-Output 'Prompt message: $greeting' # Outputs literal value
### Viewing Variable Types
$number.GetType()
### Common Variable Type Examples
| Example | Type | Example Value |
| --- | --- | --- |
| `$str = "abc"` | String | `"abc"` |
| `$num = 123` | Int32 | `123` |
| `$arr = 1, 2, 3` | Array | `[1, 2, 3]` |
| `$obj = Get-Process` | Object[] | Process list |
| `$hashtable = @{}` | Hashtable | `@{Name="Tom";Age=30}` |
* * *
## 2. Special Variables
PowerShell predefines many useful built-in variables:
| Variable Name | Description |
| --- | --- |
| `$_` | Current object being processed in pipeline |
| `$?` | Whether the last command succeeded |
| `$LASTEXITCODE` | Exit code of the last external program |
| `$PSVersionTable` | PowerShell version information |
| `$env:PATH` | Environment variable PATH |
* * *
## 3. Variable Scope Concepts
### What is Scope?
**Scope** refers to where a variable is valid. PowerShell supports multiple scope levels to ensure variables are not accidentally overwritten.
Common scopes include:
| Scope | Description |
| --- | --- |
| `Global` | Global scope, the top-level scope of a script or shell |
| `Local` | Variable in current function or code block (default scope) |
| `Script` | Variable valid within the current script file |
| `Private` | Valid only within current scope, inaccessible from outside |
### Example Demonstration: Variable Scope Differences
$global:name = "Tom" # Global variable
$name = "Alice" # Local variable
function Show-Name {
$name = "Bob" # Local variable inside function
Write-Output "Inside function: $name"
}
Show-Name
Write-Output "Outside function: $name"
Write-Output "Global variable: $global:name"
**Output:**
Inside function: Bob
Outside function: Alice
Global variable: Tom
### Explicitly Setting Scope
You can add a scope identifier before the variable name to explicitly define its visibility:
$script:dbName = "MyDatabase" # Only visible to current script
$global:apiKey = "abcdef12345" # Available everywhere
* * *
### Viewing Variables in Current Scope
Get-Variable
Or list global variables:
Get-Variable -Scope Global
* * *
## 4. Common Errors and Considerations
| Situation | Cause and Recommendation |
| --- | --- |
| Variable set inside function inaccessible outside | Did not use `global:` or `script:` to explicitly declare |
| Same-name variable overwritten | Recommend using scope prefix to distinguish important variables |
| Environment variable modification not taking effect | Use `$env:` to modify, and pay attention to scope and persistence |
* * *
## 5. Practical Examples
### Example 1: Create a function using global variable as configuration
$global:Threshold = 80
function Check-CPU {
$usage = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
if ($usage -gt $global:Threshold) {
Write-Output "CPU usage too high: $(::Round($usage, 2))%"
} else {
Write-Output "CPU usage normal: $(::Round($usage, 2))%"
}
}
### Example 2: Variable defined in function not visible outside (local scope)
function Say-Hello {
$message = "Hello, PowerShell!"
Write-Output $message
}
Say-Hello
Write-Output $message # Error: $message does not exist
### Example 3: Using `$env:` to set environment variable (temporary)
$env:MY_ENV = "HelloWorld"
Write-Output $env:MY_ENV
> Note: This method is only valid in the current PowerShell session and will expire after closing the window.
* * *
## 6. Summary
- PowerShell uses `$variableName` to define variables, with automatic type inference
- Can store arbitrary data types including strings, arrays, hashtables, objects, etc.
- Scope controls the "survival range" of variables; commonly used ones are `Local`, `Script`, `Global`
- Correctly understanding scope helps write clearly structured, maintainable scripts
- Built-in variables and environment variables are very practical, but pay attention to their scope limitations
* * *
## 7. Practice Tasks
Task 1: Define a string variable `$title` and output it:
$title = "PowerShell Learning Journey"
Write-Output $title
Task 2: Define a variable inside a function and try to access it outside the function
function Set-Message {
$msg = "From function"
Write-Output $msg
}
Set-Message
Write-Output $msg # Check if accessible
Task 3: Set and read environment variable `APP_ENV`
$env:APP_ENV = "Development"
Write-Output $env:APP_ENV
YouTip