Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PowerShell Variables and Scope

PowerShell Variables and Scope

Variables are a fundamental tool 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 their scope mechanism. Understanding scope lets you write more stable, clearer scripts and avoid variable conflicts or accidental overwriting.

This section will give you a comprehensive understanding of how to use variables in PowerShell, their data types, scope rules, and best practices.


I. Variable Basics

Define a variable

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

$greeting = "Hello, PowerShell"

$number = 100

Variable assignment does not require declaring the type in advance; PowerShell automatically infers the data type.

Reading variables

Simply reference the variable to read its value:

Write-Output $greeting

You can also embed it in a string:

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

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

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

Viewing the 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 = @{} For the Map interface and its implementation classes, refer to: @{Name="Tom";Age=30}

II. 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

III. Variable Scope Concept

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 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 only within the current scope, inaccessible from outside

Example demonstration: 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

Explicitly setting scope

You can prefix a variable name with a scope identifier to specify its visibility:

$script:dbName = "MyDatabase"  # 仅对当前脚本可见

$global:apiKey = "abcdef12345" # 对所有位置可用


View variables in the current scope

Get-Variable

Or list global variables:

Get-Variable -Scope Global


IV. Common Errors and Precautions

Problem situation Cause and suggestion
Variables set inside a function are inaccessible from outside Did not use global: or script: explicit declaration
Variables with the same name are overwritten It is recommended to use scope prefixes to distinguish important variables
Environment variable modification did not take effect Please use the $env: modify it, and pay attention to scope and persistence

V. Practical Examples

Example 1: Create a function and use a global variable 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: Define a variable inside a function that is not visible outside (local scope)

function Say-Hello {

    $message = "你好,PowerShell!"

    Write-Output $message

}



Say-Hello

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

Example 3: Use $env: to set an environment variable (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 the window is closed.


VI. Summary


VII. Practice Tasks

Task 1: Define a string variable $title and output:



$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 = "来自函数"

    Write-Output $msg

}

Set-Message

Write-Output $msg   # 查看是否能访问

Task 3: Set and read an environment variable APP_ENV

$env:APP_ENV = "Development"

Write-Output $env:APP_ENV