PowerShell 真实生产环境中的 15 个高价值实战场景
(2025 年最新版,几乎每天都在企业里被真实使用)
| 序号 | 场景名称 | 一句话说明 | 典型命令 / 脚本片段(直接可抄) |
|---|---|---|---|
| 1 | 批量重启挂死的服务 | 一键修复全公司 2000+ 台服务器上卡死的某个服务 | $computers = Get-Content servers.txtGet-Service -Name Spooler -ComputerName $computers | Where Status -eq 'Stopped' | Restart-Service -Force |
| 2 | 清理全网 C:\temp 垃圾文件 | 每周自动清理几百台服务器的临时文件,释放 TB 级空间 | Invoke-Command -ComputerName (Get-ADComputer -Filter *) -ScriptBlock { Get-ChildItem 'C:\temp','C:\Windows\Temp','$env:TEMP' -Recurse -File -ErrorAction SilentlyContinue | Where LastWriteTime -lt (Get-Date).AddDays(-7) | Remove-Item -Force} |
| 3 | 查找全公司谁还在用 Windows 7/2008 | 合规审计神器 | Get-ADComputer -Filter {OperatingSystem -like "*Windows 7*" -or OperatingSystem -like "*2008*"} -Properties OperatingSystem,LastLogonDate | Select Name,OperatingSystem,@{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogonDate)}} | Export-Csv OldOS.csv -NoType |
| 4 | 批量修改 5000 台服务器的注册表 | 比如关闭 SMBv1、开启 RDP、改电源计划等 | $regPath = "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters"$regName = "SMB1"$value = 0Invoke-Command -ComputerName (Get-Content servers.txt) -ScriptBlock { New-ItemProperty -Path $using:regPath -Name $using:regName -Value $using:value -PropertyType DWORD -Force} |
| 5 | 每天自动导出 SQL 数据库备份并清理旧备份 | 备份 + 自动清理 30 天前文件 | # 备份(SQL 模块)Backup-SqlDatabase -ServerInstance SQL01 -Database HRDB -BackupFile "\\nas\backup\HRDB_$(Get-Date -f yyyyMMdd).bak"# 清理Invoke-Command -ComputerName NAS01 -ScriptBlock { Get-ChildItem "\\nas\backup\*.*" | Where LastWriteTime -lt (Get-Date).AddDays(-30) | Remove-Item -Force } |
| 6 | 监控磁盘空间并自动发邮件告警 | 小于 10% 自动发邮件给管理员 | $threshold = 10foreach ($srv in Get-Content servers.txt) { $disk = Get-WmiObject Win32_LogicalDisk -ComputerName $srv -Filter "DriveType=3" | Where {$_.FreeSpace / $_.Size * 100 -lt $threshold} if ($disk) { Send-MailMessage -To admin@company.com -From alert@company.com -Subject "$srv 磁盘告警" -Body ($disk | Out-String) -SmtpServer mail.company.com }} |
| 7 | 一键收集所有服务器的补丁状态 | 每月生成补丁报告给安全部 | $sessions = New-PSSession (Get-Content servers.txt)Invoke-Command -Session $sessions { Get-HotFix | Select PSComputerName,HotFixID,InstalledOn,Description } | Export-Csv -Path "PatchReport_$(Get-Date -f yyyyMMdd).csv" -NoTypeRemove-PSSession $sessions |
| 8 | 批量添加用户到本地管理员组 | 运维/开发人员上机权限批量授权 | $user = "COMPANY\dev-john"$computers = Get-Content need-admin.txtInvoke-Command -ComputerName $computers -ScriptBlock { Add-LocalGroupMember -Group "Administrators" -Member $using:user} |
| 9 | 自动生成每天的 IIS 日志分析报告 | 找出访问量 Top 10 IP、404 最多的页面等 | $yesterday = (Get-Date).AddDays(-1).ToString("yyyyMMdd")Get-ChildItem "C:\inetpub\logs\LogFiles\*" -Recurse -Include "*$yesterday*.log" | Select-String 'GET|POST' | ForEach-Object { $_.Line.Split(" ") | Select-Object @{n='IP';e={$_[0]}}, @{n='URL';e={$_[5]}}, @{n='Status';e={$_[8]}} } | Group-Object IP,Status | Sort Count -Desc | Select -First 20 |
| 10 | 批量解压并导入旧备份文件 | 把几百个 .bak/.zip 自动恢复到测试库 | Get-ChildItem "D:\OldBackups\*.bak" | ForEach-Object { $dbName = "Test_$( $_.BaseName )" Restore-SqlDatabase -ServerInstance TESTSQL -Database $dbName -BackupFile $_.FullName -ReplaceDatabase} |
| 11 | 自动创建几百个 AD 用户 | 配合 CSV 批量建账号(HR 最爱) | Import-Csv 新员工清单.csv | ForEach-Object { New-ADUser -Name "$($_.姓名)" -SamAccountName $_.工号 -UserPrincipalName "$($_.工号)@company.com" -Path "OU=新员工,DC=company,DC=com" -AccountPassword (ConvertTo-SecureString "P@ssw0rd123" -AsPlainText -Force) -Enabled $true} |
| 12 | 一键关闭所有打开的 Excel 进程并释放锁文件 | 财务每月结账必备神器 | Get-Process excel -ErrorAction SilentlyContinue | Stop-Process -ForceGet-ChildItem "\\fileserver\财务共享\*.xlsx" -Include ~$* -File | Remove-Item -Force |
| 13 | 自动巡检 1000+ 台服务器的安全基线 | 防火墙、杀毒、补丁、账户策略等一次性出报告 | 用 Microsoft 官方的 Security Compliance Toolkit + PowerShell 自动化(太长可单独要脚本) |
| 14 | 批量修改 Office 365 用户的许可证 | 有人离职、有人晋升,批量改 License | Connect-MSOLService$users = Import-Csv 要改License的用户.csvforeach ($u in $users) { Set-MsolUserLicense -UserPrincipalName $u.UPN -RemoveLicenses "company:ENTERPRISEPACK" -AddLicenses "company:ENTERPRISEPREMIUM"} |
| 15 | 每日自动生成“公司 IT 资产总表” | 服务器、IP、系统、CPU、内存、磁盘、负责人一键导出 | Get-ADComputer -Filter * -Properties * | Select Name,OperatingSystem,OperatingSystemVersion,IPv4Address,LastLogonDate,Description | Export-Excel "IT资产总表_$(Get-Date -f yyyyMMdd).xlsx" -AutoSize -TableName Assets |
真正被用烂的“万金油”脚本(建议每个人桌面放一份)
# 文件名:运维神器一键菜单.ps1
Add-Type -AssemblyName System.Windows.Forms
$form = New-Object Windows.Forms.Form
$form.Text = "运维日常工具箱 v2025"
$buttons = @(
"重启Spooler服务","清理Temp垃圾","查补丁状态","查磁盘空间<15%","批量加本地管理","关闭Excel释放锁","生成资产表"
)
$y = 20
foreach ($text in $buttons) {
$btn = New-Object Windows.Forms.Button
$btn.Text = $text
$btn.Top = $y
$btn.Width = 280
$btn.Height = 40
$btn.Add_Click({ Invoke-Expression ".& '$PSScriptRoot\$($this.Text).ps1'" })
$form.Controls.Add($btn)
$y += 50
}
$form.ShowDialog()
把上面这些脚本往死里用 + 稍微改改参数,就能解决 95% 的日常运维、自动化、审计需求。
想要其中任意一个脚本的完整版(带日志、邮件通知、错误处理、企业模板),直接告诉我编号,我立刻发给你现成可用的生产版本!