蓝色天空网mbsky.com · 知识 · 实践 · 创造PowerShell · 本地阅读预览
教程 / .NET / PowerShell

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 bytesHTTP500精确筛选不以全文含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-RestMethodURI/状态/JSON结构化响应自有回环成功/404/坏JSON分别检查
ADO.NET / SQL Server连接/参数查询/reader数据库行真实库/驱动/认证未运行,Dispose需配套
Excel COMApplication/Workbook/Worksheet单元格及保存Windows Excel环境,Close/Quit/释放未运行

本章独立核心源码与验证步骤

powershell · 阅读源码
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}
PowerShell 实战:可预检文件任务、日志和本地API:本章独立本地实验

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

当前源码 SHA256:d406844e859a301f8cf0b2b1083c6f36942e9edf9a2261e3873194c38302b023

下载本站示例源码
预期结果 · 待实际运行核验
  • 有序log_001/log_002重命名、WhatIf保留文件后真实仅删过期自有文件。
  • 日志仅status500计1,不误计URL/字节500;SHA256/旧MD5、HTTP/404/坏JSON核对;远程SQL/Excel不执行。

常见错误与边界

  • 把累计CPU秒数写成百分比。
  • 把非终止错误、全局作用域或当前用户持久策略理解错。
  • 用本地替代冒充真实服务/远程/账户/SQL/Office通过。

练习与解答

仅在新建测试目录改变一个固定输入,先列出预期、目标及清理方式,再核对真实输出。

展开参考解答

先发现命令和参数,分清类型/输出流/作用域;副作用限定在自己创建的目标,未具备的管理环境不标完成。

规范与官方依据