2024-05-02发表2025-03-25更新powershell / scripting1 分钟读完 (大约134个字)PowerShell变量作用域深度解析基础作用域类型1234567$global:counter = 10 # 全局作用域function Show-Count { $script:total = 20 # 脚本作用域 $local:temp = 5 # 局部作用域 $global:counter + $script:total + $local:temp} 作用域穿透技巧1234567# 使用Get-Variable跨作用域访问Get-Variable counter -Scope Global# 使用Set-Variable修改父作用域function Update-Count { Set-Variable -Name counter -Value 15 -Scope 1} 最佳实践 优先使用参数传递替代跨作用域访问 谨慎使用global作用域 在模块中使用$script作用域保持状态 使用private修饰符保护关键变量