PowerShell Variables and Scopes

Variables are fundamental tools in any programming language, and PowerShell is no exception.

We can use variables to store numbers, strings, objects, arrays, hash tables... What truly makes PowerShell variables powerful is its scope mechanism. Understanding scope allows you to write more stable and clearly structured scripts, avoiding variable conflicts or accidental overwrites.

This section will give you a comprehensive understanding of variable usage, data types, scope rules, and best practices in PowerShell.


1. Variable Basics

Defining Variables

In PowerShell, variables begin with a dollar sign ($), followed by the variable name.

$greeting = "Hello, PowerShell"
$number = 100

Variable assignment does not require declaring a type beforehand; PowerShell automatically infers the data type.

Reading Variables

You can read a variable's value by directly referencing it:

Write-Output $greeting

It can also be inserted into strings:

Write-Output "提示信息:$greeting"

If the string uses single quotes, the variable will not be parsed:

Write-Output '提示信息:$greeting'   # 输出字面值

Viewing Variable Type

$number.GetType()

Examples of Common Variable Types

Example Type Example Value
$str = "abc" String "abc"
$num = 123 Integer (Int32) 123
$arr = 1, 2, 3 Array [1, 2, 3]
$obj = Get-Process Object Collection (Object[]) Process List
$hashtable = @{} Hashtable @{Name="Tom";Age=30}

2. Special Variables


PowerShell predefines many useful built-in variables:

Variable Name Description
$_ The object currently being processed in the pipeline
$? Whether the previous command succeeded
$LASTEXITCODE The exit code of the previous external program
$PSVersionTable PowerShell version information
$env:PATH Environment variable PATH

3. Variable Scope Concepts

What is Scope?

ScopeRefers 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 the script or shell
Local Variables in the current function or code block (default scope)
Script Variables valid in the current script file
Private Valid within the current scope, inaccessible from outside

Example Demo: Variable Scope Differences

$global:name = "Tom"       # 全局变量
$name = "Alice"            # 本地变量
function Show-Name {
    $name = "Bob"          # 函数内的局部变量
    Write-Output "函数内部:$name"
}

Show-Name
Write-Output "函数外部:$name"
Write-Output "全局变量:$global:name"

Output result:

函数内部:Bob
函数外部:Alice
全局变量:Tom

Setting Scope Explicitly

You can add a scope identifier before the variable name to specify the variable's visibility range:

$script:dbName = "MyDatabase"  # 仅对当前脚本可见
$global:apiKey = "abcdef12345" # 对所有位置可用

Viewing Variables in Current Scope

Get-Variable

Or list global variables:

Get-Variable -Scope Global

4. Common Errors and Notes

Problem Scenario Cause and Suggestion
Variables set inside a function cannot be accessed externally Not usingglobal:orscript:Explicit declaration
Variables with the same name are overwritten It is recommended to use scope prefixes to distinguish important variables
Environment variable modifications do not take effect Please use$env:to modify, and pay attention to scope and persistence

5. Practical Examples

Example 1: Create a Function and Use Global Variables as Configuration

$global:Threshold = 80

function Check-CPU {
    $usage = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples[0].CookedValue
    if ($usage -gt $global:Threshold) {
        Write-Output "CPU 使用率过高:$([math]::Round($usage, 2))%"
    } else {
        Write-Output "CPU 使用率正常:$([math]::Round($usage, 2))%"
    }
}

Example 2: Variables Defined in a Function Are Not Visible Externally (Local Scope)

function Say-Hello {
    $message = "你好,PowerShell!"
    Write-Output $message
}

Say-Hello
Write-Output $message   # 报错:$message 不存在

Example 3: Using$env:Setting Environment Variables (Temporary)

$env:MY_ENV = "HelloWorld"
Write-Output $env:MY_ENV

Note: This method is only valid in the current PowerShell session and becomes invalid after closing the window.


6. Summary

  • PowerShell uses$variable_nameto define variables, with automatic type inference
  • Can store any data type, including strings, arrays, hash tables, objects, etc.
  • Scope controls the "living range" of variables; commonly used ones includeLocal、Script、Global
  • Correctly understanding scope helps in writing clearly structured and highly 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$titleand output it:

$title = "PowerShell 学习之旅"
Write-Output $title

Task 2: Define a Variable in a Function and Try to Access It Outside the Function

function Set-Message {
    $msg = "来自函数"
    Write-Output $msg
}
Set-Message
Write-Output $msg   # 查看是否能访问

Task 3: Set and Read Environment VariablesAPP_ENV

$env:APP_ENV = "Development"
Write-Output $env:APP_ENV
Other Extensions