PowerShell 实战:可预检文件任务、日志和本地API
保留本地自动化、远程及技术集成,分清实际运行与环境待验。
学完这一章,你能够
- 保留本地自动化、远程及技术集成,分清实际运行与环境待验。
- 保留本地自动化、远程及技术集成,分清实际运行与环境待验。
重命名、清理和信息
批量重命名前稳定排序并生成旧→新计划,检测目标冲突,避免已有log_001与新输入互相覆盖;两阶段临时名或明确拒绝按场景选择。
清理以固定截止时间只处理本工程自建目录中的文件,先-WhatIf再实际删除过期自有文件;不碰Windows\Temp。真实定时任务创建/调度仍待验,单次运行不是定时功能已完成。
系统信息的CIM/OS/CPU/RAM与运行时对象分别记录,公开输出只含教学最小字段,不泄漏机器账号或硬件序列号。
日志与远程管理
IIS等日志应按#Fields或明确定义列解析,全文-match "500"会误匹配URL或字节,不能等同HTTP状态500。实例只在自有日志按status字段筛选并生成报告。
WinRM/SSH、Invoke-Command单/多主机、New/Enter/Remove-PSSession和Credential都保留说明;不启用本机远程、不输入凭据、不连接任意Server01。远程传输加密与身份配置按实际方案,不简单宣称HTTP永远明文。
.NET哈希和本地REST
MD5可解释历史校验但不用于安全完整性,本例同时计算SHA256及旧MD5并核对;算法对象需要Dispose,优先Get-FileHash或流方式,避免大文件一次读满内存。
天气接口需要密钥、服务条款和错误处理,本例替换为自有回环JSON并明确不是抓到原天气结果。HTTP成功/404/无效JSON分别记录,不伪造外部温度。
数据库、Office及资源释放
SQL Server需真实服务器、驱动和认证;参数化查询、连接/reader/command的Dispose及异常处理不可漏。Excel COM仅适用具备Excel的Windows交互环境,保存、Close/Quit与释放资源要对应,不偷偷打开可见Excel。
数据库/Office/远程环境当前未执行,附独立待验说明和不默认运行的范例;它们不能被本地对象或JSON演示顶替后标已完成。
命令与参数参考
| 命令 | 关键输入 | 结果/作用 | 环境、错误与边界 |
| Get-ChildItem/Rename-Item | 稳定排序、旧→新计划 | 确定性批量重命名 | 先预检冲突/绝对目标 |
| Get-Date/AddDays/Remove-Item | 固定截止时间/-WhatIf | 筛过期文件/预演/删除 | 仅自建测试文件,实际与预演分别验证 |
| Task Scheduler | 计划和身份条件 | 定时运行 | 本轮未创建任务 |
| 日志字段解析 | 明确date uri status bytes | HTTP500精确筛选 | 不以全文含500替代 |
| Invoke-Command | -ComputerName/-Session/-ScriptBlock | 远程命令 | 真实端点与授权待验 |
| New/Enter/Remove-PSSession | 主机/会话 | 会话生命周期 | WinRM/SSH、认证和传输待验 |
| Get-Credential | 凭据交互 | PSCredential | 本轮不输入/存储密码 |
| Get-FileHash | -Algorithm SHA256/MD5 | 校验文本 | MD5仅历史;不作安全完整性 |
| MD5.Create/ComputeHash/Dispose | 自有字节数组 | 历史算法对照 | 释放对象,生产大文件用流 |
| Invoke-RestMethod | URI/状态/JSON | 结构化响应 | 自有回环成功/404/坏JSON分别检查 |
| ADO.NET / SQL Server | 连接/参数查询/reader | 数据库行 | 真实库/驱动/认证未运行,Dispose需配套 |
| Excel COM | Application/Workbook/Worksheet | 单元格及保存 | Windows Excel环境,Close/Quit/释放未运行 |
本章独立核心源码与验证步骤
展开查看收起
param([string]$BaseUrl='http://127.0.0.1:8771')
. (Join-Path $PSScriptRoot 'lab.ps1')
$root=New-LearningDirectory
try {
$inputs=New-Item -Path (Join-Path $root 'inputs') -ItemType Directory
foreach($name in @('b.txt','a.txt')){Set-Content -LiteralPath (Join-Path $inputs.FullName $name) -Value $name}
$files=@(Get-ChildItem -LiteralPath $inputs.FullName -File -Filter '*.txt'|Sort-Object Name);$counter=1;$plan=@(foreach($f in $files){[pscustomobject]@{Old=$f.FullName;New=('log_{0:D3}.txt' -f $counter)};$counter++})
Assert-Learning (($plan.New -join ',') -eq 'log_001.txt,log_002.txt') 'stable rename plan'
foreach($row in $plan){$target=Assert-LearningPath -Path (Join-Path $inputs.FullName $row.New) -Root $root;if(Test-Path -LiteralPath $target){throw 'rename collision before any move'}}
foreach($row in $plan){$safe=Assert-LearningPath -Path $row.Old -Root $root;Rename-Item -LiteralPath $safe -NewName $row.New}
Assert-Learning ((Get-Content -LiteralPath (Join-Path $inputs.FullName 'log_001.txt')).Trim() -eq 'a.txt') 'actual deterministic rename'
$cutoff=[datetime]'2026-11-01T00:00:00Z';$old=Join-Path $root 'old.tmp';$new=Join-Path $root 'new.tmp';Set-Content -LiteralPath $old -Value 'old';Set-Content -LiteralPath $new -Value 'new';(Get-Item -LiteralPath $old).LastWriteTimeUtc=$cutoff.AddDays(-8);(Get-Item -LiteralPath $new).LastWriteTimeUtc=$cutoff
$expired=@(Get-ChildItem -LiteralPath $root -File -Filter '*.tmp'|Where-Object {$_.LastWriteTimeUtc -lt $cutoff.AddDays(-7)})
Assert-Learning ($expired.Count -eq 1) 'only old own file'
foreach($file in $expired){$safe=Assert-LearningPath -Path $file.FullName -Root $root;Remove-Item -LiteralPath $safe -WhatIf 6>$null}
Assert-Learning (Test-Path -LiteralPath $old) 'WhatIf did not delete'
foreach($file in $expired){$safe=Assert-LearningPath -Path $file.FullName -Root $root;Remove-Item -LiteralPath $safe}
Assert-Learning (-not(Test-Path -LiteralPath $old) -and (Test-Path -LiteralPath $new)) 'real owned expiry deletion'
$log=Join-Path $root 'requests.log';@('#Fields: date uri status bytes','2026-11-01 /ok500 200 500','2026-11-01 /error 500 20','2026-11-01 /missing 404 5')|Set-Content -LiteralPath $log
$errors=@(Get-Content -LiteralPath $log|Where-Object {$_ -notlike '#*'}|ForEach-Object {$v=$_ -split '\s+';[pscustomobject]@{Date=$v[0];Uri=$v[1];Status=[int]$v[2];Bytes=[int]$v[3]}}|Where-Object Status -eq 500)
Assert-Learning ($errors.Count -eq 1 -and $errors[0].Uri -eq '/error') 'status field not substring500'
$bytes=[Text.Encoding]::UTF8.GetBytes('mbsky.com');$hashFile=Join-Path $root 'hash.txt';[IO.File]::WriteAllBytes($hashFile,$bytes)
$sha=(Get-FileHash -LiteralPath $hashFile -Algorithm SHA256).Hash;$md5=[Security.Cryptography.MD5]::Create();try{$legacy=[Convert]::ToHexString($md5.ComputeHash($bytes))}finally{$md5.Dispose()}
Assert-Learning ($sha.Length -eq 64 -and $legacy -eq (Get-FileHash -LiteralPath $hashFile -Algorithm MD5).Hash) 'actual hash legacy and modern'
Assert-Learning (([uri]$BaseUrl).Host -eq '127.0.0.1') 'local API only'
$api=Invoke-RestMethod -Uri ($BaseUrl+'/learning') -TimeoutSec 5;Assert-Learning ($api.lessons -eq 3) 'real API response'
$httpError=$false;try{Invoke-RestMethod -Uri ($BaseUrl+'/missing') -TimeoutSec 5}catch{$httpError=$true};Assert-Learning $httpError 'HTTP404 caught'
$badJson=$false;try{$bad=Invoke-WebRequest -Uri ($BaseUrl+'/bad-json') -TimeoutSec 5;$bad.Content|ConvertFrom-Json}catch{$badJson=$true};Assert-Learning $badJson 'invalid JSON caught'
Write-LearningReport 'powershell-practice' @{rename_targets=$plan.New;expired_owned_files=$expired.Count;whatif_preserved=$true;actual_expired_removed=$true;status500_rows=$errors.Count;sha256=$sha;legacy_md5=$legacy;local_api_site=$api.site;http404_caught=$httpError;bad_json_caught=$badJson;remote_sql_office_and_scheduled_tasks_executed=$false}
}finally{Remove-LearningDirectory $root}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
- 有序log_001/log_002重命名、WhatIf保留文件后真实仅删过期自有文件。
- 日志仅status500计1,不误计URL/字节500;SHA256/旧MD5、HTTP/404/坏JSON核对;远程SQL/Excel不执行。
本章附件与实例包
常见错误与边界检查
- 把累计CPU秒数写成百分比。
- 把非终止错误、全局作用域或当前用户持久策略理解错。
- 用本地替代冒充真实服务/远程/账户/SQL/Office通过。
技术规范与官方资料
练习与参考解答
查看参考解答
先发现命令和参数,分清类型/输出流/作用域;副作用限定在自己创建的目标,未具备的管理环境不标完成。