PowerShell 实际应用

PowerShell 不只是一个终端工具,它是 Windows 环境下功能最全面的自动化平台之一。

本节将通过 三大类实际应用场景,展示 PowerShell 在日常管理、远程运维、跨技术集成中的强大能力:

  • 日常管理任务自动化

  • 远程管理

  • 与其他技术集成


一、日常管理任务自动化

1.1 批量文件重命名

需求:

将一个目录下的所有 .txt 文件重命名为统一前缀加序号的形式,如:log_001.txtlog_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++}

定时清理临时文件

示例:删除 7 天前的临时文件

$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 基础

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 Framework

PowerShell 内建对 .NET 类库的访问能力,几乎可以调用所有 .NET API。

示例:获取文件 MD5 值

$targetPath = "C:\Windows\Temp"Get-ChildItem -Path $targetPath -Recurse |
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } |
    Remove-Item -Force -Recurse2

调用 REST API

示例:调用 JSON 接口获取天气信息

$targetPath = "C:\Windows\Temp"Get-ChildItem -Path $targetPath -Recurse |
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } |
    Remove-Item -Force -Recurse3

数据库连接基础(以 SQL Server 为例)

$targetPath = "C:\Windows\Temp"Get-ChildItem -Path $targetPath -Recurse |
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } |
    Remove-Item -Force -Recurse4

与 Office 应用程序交互

示例:使用 Excel COM 对象写入数据

$targetPath = "C:\Windows\Temp"Get-ChildItem -Path $targetPath -Recurse |
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } |
    Remove-Item -Force -Recurse5

四、小结

应用类型实际用途技术点
本地自动化批量重命名、清理文件、系统信息文件系统、定时器、对象
日志分析检查错误日志并生成报告文本处理、过滤、导出
远程运维多主机批量操作、远程会话Invoke-CommandPSSession
技术集成与 REST API、数据库、Excel 联动Invoke-RestMethod, COM, ADO.NET
.NET 支持调用底层 API 实现扩展功能使用 .NET 类库