蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

PowerShell 变量与作用域:遮蔽、输出和环境生命周期:本章独立本地实验

POWERSHELLWindows / PowerShell7.6.5 / 同包自有文件、进程、回环JSON;其它平台和管理环境待验powershell-variables-and-scope.ps1
powershell-variables-and-scope.ps114 行
. (Join-Path $PSScriptRoot 'lab.ps1')
$global:mbskyScopeMarker='global'
$inside=& (Join-Path $PSScriptRoot 'scope-demo.ps1')
Assert-Learning ($inside.Local -eq 'child' -and $inside.Script -eq 'script' -and $inside.Global -eq 'global') 'three actually distinct scopes'
Assert-Learning ($global:mbskyScopeMarker -eq 'global') 'nested script did not overwrite global'
if($true){$mbskyIfValue='same-scope'};Assert-Learning ($mbskyIfValue -eq 'same-scope') 'if block not new scope'
$privateVisible=& {$private:mbskyPrivateMarker='secret-example'; & { $null -ne (Get-Variable -Name mbskyPrivateMarker -ErrorAction SilentlyContinue) }}
Assert-Learning (-not $privateVisible) 'private hidden from child'
$loose=& {Set-StrictMode -Off;$null -eq $mbskyNeverDefined};$strictError=& {Set-StrictMode -Version Latest;try{$null=$mbskyNeverDefined;$false}catch{$true}}
Assert-Learning ($loose -and $strictError) 'undefined null vs strict error'
$envBefore=[Environment]::GetEnvironmentVariable('MBSKY_LEARNING_TOKEN','Process')
try {$env:MBSKY_LEARNING_TOKEN='mbsky-temporary';Assert-Learning ($env:MBSKY_LEARNING_TOKEN -eq 'mbsky-temporary') 'owned environment variable';Write-LearningReport 'powershell-variables-and-scope' @{scopes=$inside;if_block_same_scope=$true;private_hidden=$true;undefined_without_strict_is_null=$loose;undefined_strict_error=$strictError;temporary_env_value=$env:MBSKY_LEARNING_TOKEN;environment_persistence_changed=$false}}
finally{[Environment]::SetEnvironmentVariable('MBSKY_LEARNING_TOKEN',$envBefore,'Process');Remove-Variable -Name mbskyScopeMarker -Scope Global}
本例需在 Windows / PowerShell7.6.5 / 同包自有文件、进程、回环JSON;其它平台和管理环境待验 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows / PowerShell7.6.5 / 同包自有文件、进程、回环JSON;其它平台和管理环境待验

入口文件:projects/powershell-lab/powershell-variables-and-scope.ps1

预期结果与验证条件观察提示
  • 嵌套文件实际Local=child/Script=script/Global=global;if同scope,Private子scope不可见。
  • 无严格模式未定义为null,严格模式报错;自有环境变量设置后恢复。

请结合实际环境逐项观察。

附件与关联工程包下载

下载课程关联工程包:PowerShell

课程关联工程包(登记关联16章) · 含当前章节或实例 · mbskycom202611a525.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习