PowerShell 不只是一个终端工具,它是 Windows 环境下功能最全面的自动化平台之一。
本节将通过 三大类实际应用场景,展示 PowerShell 在日常管理、远程运维、跨技术集成中的强大能力:
日常管理任务自动化
远程管理
与其他技术集成
将一个目录下的所有 .txt
文件重命名为统一前缀加序号的形式,如:log_001.txt
、log_002.txt
等。
$files = Get-ChildItem -Path "D:\Logs" -Filter "*.txt"$count = 1foreach ($file in $files) { $newName = "log_{0:D3}.txt" -f $count Rename-Item -Path $file.FullName -NewName $newName $count++}
$targetPath = "C:\Windows\Temp"Get-ChildItem -Path $targetPath -Recurse | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | Remove-Item -Force -Recurse
建议将脚本保存为 .ps1
文件后,使用任务计划程序(Task SC++heduler)定期执行。
$info = [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME OSVersion = (Get-CimInstance Win32_OperatingSystem).Caption Uptime = ((Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime).ToString() CPU = (Get-CimInstance Win32_Processor).Name RAM_GB = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 2)}$info | Format-List
$logPath = "C:\inetpub\logs\LogFiles\W3SVC1\*.log"$lines = Get-Content $logPath | Where-Object { $_ -match "500" }$lines.Count$lines | Out-File "C:\Reports\error_500_report.txt"
PowerShell Remoting 是通过 WinRM 实现远程命令执行的机制。
开启远程功能(管理员运行):
Enable-PSRemoting -Force
Invoke-Command
执行远程命令Invoke-Command -ComputerName "Server01" -ScriptBlock { Get-Service -Name "W32Time"}
支持多个主机批量执行:
$servers = @("Server01", "Server02")Invoke-Command -ComputerName $servers -ScriptBlock { Get-Process | Where-Object { $_.CPU -gt 100 }}
建立会话:
$session = New-PSSession -ComputerName "Server01"
进入会话:
Enter-PSSession $session
执行命令:
Invoke-Command -Session $session -ScriptBlock { Get-Date }
关闭会话:
$targetPath = "C:\Windows\Temp"Get-ChildItem -Path $targetPath -Recurse | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | Remove-Item -Force -Recurse0
使用 HTTPS 而非 HTTP(配置证书)
避免使用明文密码,推荐使用凭据对象:
$targetPath = "C:\Windows\Temp"Get-ChildItem -Path $targetPath -Recurse | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | Remove-Item -Force -Recurse1
PowerShell 内建对 .NET 类库的访问能力,几乎可以调用所有 .NET API。
$targetPath = "C:\Windows\Temp"Get-ChildItem -Path $targetPath -Recurse | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | Remove-Item -Force -Recurse2
$targetPath = "C:\Windows\Temp"Get-ChildItem -Path $targetPath -Recurse | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | Remove-Item -Force -Recurse3
$targetPath = "C:\Windows\Temp"Get-ChildItem -Path $targetPath -Recurse | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | Remove-Item -Force -Recurse4
$targetPath = "C:\Windows\Temp"Get-ChildItem -Path $targetPath -Recurse | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | Remove-Item -Force -Recurse5
应用类型 | 实际用途 | 技术点 |
---|---|---|
本地自动化 | 批量重命名、清理文件、系统信息 | 文件系统、定时器、对象 |
日志分析 | 检查错误日志并生成报告 | 文本处理、过滤、导出 |
远程运维 | 多主机批量操作、远程会话 | Invoke-Command , PSSession |
技术集成 | 与 REST API、数据库、Excel 联动 | Invoke-RestMethod , COM, ADO.NET |
.NET 支持 | 调用底层 API 实现扩展功能 | 使用 .NET 类库 |