PowerShell 基本语法:类型、运算、函数与错误流
保留注释、变量、全部运算类型、分支循环和函数,实际验证catch条件。
学完这一章,你能够
- 保留注释、变量、全部运算类型、分支循环和函数,实际验证catch条件。
- 保留注释、变量、全部运算类型、分支循环和函数,实际验证catch条件。
注释、类型和字符串
#与<# #>是单/多行注释;变量$开头,可动态存值也可用[int]等约束。字符串、整数、Double小数、布尔、数组及哈希表各有.NET类型;“弱类型”不能替代实际转换和约束规则。
双引号插值,单引号通常保留字面值,$()计算表达式。$null没有可直接GetType的对象;集合被展开时0/1/多条输出的形状也要留意。
运算、条件和循环
+ - * / %、-eq/-ne/-lt/-le/-gt/-ge、-and/-or/-not、-like/-match/-replace与-in/-contains逐项有不同职责;比较默认常不区分大小写,-ceq可显式区分。
if/elseif/else、for、foreach、while都需明确终止条件;本例固定有限输入并校验各分支、次数和集合结果,不执行无限轮询。
函数和错误处理
param声明输入,函数把所有成功流输出作为结果;return会结束当前函数,但不会撤回此前已输出的值。调试说明不应混到业务结果数组。
try/catch捕获终止错误,Get-Item缺文件通常为非终止错误,需要-ErrorAction Stop或合适的Preference才进入catch;不能照抄只包try就承诺捕获。finally清理资源,异常实际类型按错误记录核对。
知识、流程与适用条件
| 条目 | 职责/含义 | 条件与限制 |
| # / <# #> | 注释 | 代码/字符串上下文分别处理 |
| String/Int32/Double/Boolean | 基本类型 | 类型约束和转换可失败 |
| Array/Hashtable/PSCustomObject | 集合及记录 | 成功流可展开为0/1/多项 |
| 单双引号/$() | 字面/插值/表达式 | 按源码实测 |
| + - * / % | 算术 | 数组逗号优先级需括号 |
| -eq/-ne/-lt/-le/-gt/-ge | 比较 | 默认大小写行为,-ceq显式区分 |
| -and/-or/-not | 逻辑 | 括号与求值顺序 |
| -like/-match/-replace | 通配/正则/替换 | 并非同一语法 |
| -in/-contains | 集合包含 | 方向不同 |
| if/elseif/else与循环 | 控制流 | 固定有限输入 |
| function/param/return | 复用和成功流 | return不撤回先前输出 |
| try/catch/finally | 异常/清理 | 终止错误才进入catch |
本章独立核心源码与验证步骤
展开查看收起
powershell
. (Join-Path $PSScriptRoot 'lab.ps1')
# Line comment; this must stay outside strings.
<# Block comment remains parser input, not execution. #>
$label='sky';$number=7;$decimal=3.14;$flag=$true;$array=@(1,2,3);$map=@{Name='mbsky';Count=3}
$types=@($label.GetType().Name,$number.GetType().Name,$decimal.GetType().Name,$flag.GetType().Name,$array.GetType().Name,$map.GetType().Name)
Assert-Learning (($types -join ',') -eq 'String,Int32,Double,Boolean,Object[],Hashtable') 'types'
$math=@((7+2),(7-2),(7*2),(7/2),(7%2));Assert-Learning (($math -join ',') -eq '9,5,14,3.5,1') 'arithmetic'
$compare=@((5 -eq 5),(5 -ne 4),(3 -lt 4),(4 -le 4),(5 -gt 4),(5 -ge 5));Assert-Learning (@($compare | Where-Object {$_ -ne $true}).Count -eq 0) 'comparisons'
Assert-Learning (($true -and -not $false) -and ($false -or $true)) 'logic'
Assert-Learning (('abc' -like 'a*') -and ('abc' -match '^a') -and ('abc' -replace 'a','s') -eq 'sbc') 'patterns'
Assert-Learning ((2 -in $array) -and ($array -contains 2) -and ('A' -eq 'a') -and -not('A' -ceq 'a')) 'membership and case'
$branches=@(50,70,95 | ForEach-Object {if($_ -ge 90){'high'}elseif($_ -ge 60){'pass'}else{'retry'}})
Assert-Learning (($branches -join ',') -eq 'retry,pass,high') 'all condition branches'
$forValues=@(for($i=1;$i -le 5;$i++){$i});$foreachValues=@(foreach($item in $array){$item*2});$whileValues=@();$counter=0;while($counter -lt 3){$whileValues+=,$counter;$counter++}
Assert-Learning (($forValues -join ',') -eq '1,2,3,4,5' -and ($foreachValues -join ',') -eq '2,4,6' -and ($whileValues -join ',') -eq '0,1,2') 'loops'
function Get-LearningOutput {param([int]$Value) 'earlier';return $Value*$Value}
$functionValues=@(Get-LearningOutput 5);Assert-Learning ($functionValues.Count -eq 2 -and $functionValues[1] -eq 25) 'return does not retract earlier output'
$root=New-LearningDirectory
try {$caught=$false;try {Get-Item -LiteralPath (Join-Path $root 'absent') -ErrorAction Stop}catch{$caught=$true};Assert-Learning $caught 'terminating missing item caught';Write-LearningReport 'powershell-basic-syntax' @{types=$types;arithmetic=$math;branches=$branches;for=$forValues;foreach=$foreachValues;while=$whileValues;function_outputs=$functionValues;missing_item_caught=$caught;single_quote='$label';double_quote="$label"}}
finally{Remove-LearningDirectory $root}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
- 6类类型、算术9/5/14/3.5/1、全部比较/逻辑/模式/包含及三级条件实际核对。
- 三种循环次数、函数两个成功输出及缺文件终止错误捕获。
本章附件与实例包
课程关联工程包(登记关联16章) · 含当前章节或实例 · mbskycom202611a525.zip
常见错误与边界检查
- 把累计CPU秒数写成百分比。
- 把非终止错误、全局作用域或当前用户持久策略理解错。
- 用本地替代冒充真实服务/远程/账户/SQL/Office通过。
技术规范与官方资料
练习与参考解答
查看参考解答
先发现命令和参数,分清类型/输出流/作用域;副作用限定在自己创建的目标,未具备的管理环境不标完成。