PowerShell使用两层foreach循环清理多机缓存并输出日志求助
PowerShell 跨机批量缓存清理脚本优化方案
现有代码核心问题
- 未启用PowerShell远程调用能力,所有路径均指向本地,无法对目标远程计算机生效
- 缺失「单台计算机→计算机内用户」的双层遍历逻辑,执行顺序不符合需求
- 存在大量冗余代码:重复读取CSV文件、Firefox缓存路径重复定义、中间临时文件
users.csv完全没必要生成 - 无错误捕获、状态输出、日志记录能力,无法回溯执行结果
- 存在语法错误:变量未加
$标识符、路径拼接错误、部分路径存在换行导致语法异常
前置要求
- 所有目标计算机已开启WinRM远程管理服务
- 脚本执行账号拥有所有目标计算机的本地管理员权限
- 计算机列表CSV文件第一列列名为
Name,内容为目标计算机的主机名/IP地址
优化后完整脚本
# 配置参数 $ComputerListPath = "C:\Temp\ComputerList.csv" $LogPath = "C:\Temp\CleanCache_$(Get-Date -Format 'yyyyMMdd_HHmmss').log" $ChromeCleanItems = @('Archived History','Cache\*','Cookies','History','Login Data','Top Sites','Visited Links','Web Data') # 日志记录函数 function Write-Log { param( [Parameter(Mandatory=$true)] [string]$Message, [ValidateSet('INFO','SUCCESS','ERROR')] [string]$Level = 'INFO' ) $logLine = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] [$Level] $Message" Add-Content -Path $LogPath -Value $logLine -Encoding UTF8 Write-Host $logLine } Write-Log "=== 批量缓存清理任务启动 ===" # 导入计算机列表 try { $computerList = Import-Csv -Path $ComputerListPath -Encoding UTF8 Write-Log "成功读取计算机列表,共$($computerList.Count)台目标计算机" } catch { Write-Log "读取计算机列表失败:$_" -Level ERROR exit 1 } # 第一层遍历:所有目标计算机 foreach ($computer in $computerList.Name) { Write-Log "开始处理计算机:$computer" # 检测计算机连通性 if (-not (Test-Connection -ComputerName $computer -Count 1 -Quiet -ErrorAction SilentlyContinue)) { Write-Log "计算机$computer不可达,跳过处理" -Level ERROR continue } try { # 远程执行清理逻辑 Invoke-Command -ComputerName $computer -ScriptBlock { param($ChromeCleanItems) # 1. 清理系统公共临时目录 try { Remove-Item -Path "C:\Windows\Temp\*" -Recurse -Force -ErrorAction Stop Write-Host "[$env:COMPUTERNAME] 系统公共临时目录清理成功" } catch { Write-Host "[$env:COMPUTERNAME] 系统公共临时目录清理失败:$_" } # 2. 获取本地所有用户目录 $userList = Get-ChildItem -Path "C:\Users" -Directory | Select-Object -ExpandProperty Name Write-Host "[$env:COMPUTERNAME] 共检测到$($userList.Count)个用户目录" # 第二层遍历:单台计算机内所有用户 foreach ($user in $userList) { Write-Host "[$env:COMPUTERNAME] 开始处理用户:$user" $userLocalPath = "C:\Users\$user\AppData\Local" # 清理Chrome缓存 try { $chromePath = "$userLocalPath\Google\Chrome\User Data\Default" if (Test-Path $chromePath) { # 杀掉Chrome进程 Get-Process chrome -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue Start-Sleep -Seconds 3 foreach ($item in $ChromeCleanItems) { $fullPath = "$chromePath\$item" if (Test-Path $fullPath) { Remove-Item -Path $fullPath -Recurse -Force -ErrorAction Stop } } Write-Host "[$env:COMPUTERNAME][$user] Chrome缓存清理成功" } } catch { Write-Host "[$env:COMPUTERNAME][$user] Chrome缓存清理失败:$_" } # 清理IE缓存 try { $iePath = "$userLocalPath\Microsoft\Windows\INetCache\*" if (Test-Path $iePath) { Remove-Item -Path $iePath -Recurse -Force -ErrorAction Stop } Write-Host "[$env:COMPUTERNAME][$user] IE缓存清理成功" } catch { Write-Host "[$env:COMPUTERNAME][$user] IE缓存清理失败:$_" } # 清理Firefox缓存 try { $firefoxProfilePath = "$userLocalPath\Mozilla\Firefox\Profiles\*.default*" if (Test-Path $firefoxProfilePath) { Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue Start-Sleep -Seconds 3 Get-ChildItem -Path $firefoxProfilePath -Directory | ForEach-Object { $cachePath = "$($_.FullName)\cache\*" if (Test-Path $cachePath) { Remove-Item -Path $cachePath -Recurse -Force -ErrorAction Stop } # 清理缓存相关sqlite文件 Get-ChildItem -Path $_.FullName -Filter "*.sqlite" -Name "cookies.sqlite","webappstore.sqlite","chromeappstore.sqlite" | Remove-Item -Force -ErrorAction Stop } Write-Host "[$env:COMPUTERNAME][$user] Firefox缓存清理成功" } } catch { Write-Host "[$env:COMPUTERNAME][$user] Firefox缓存清理失败:$_" } } } -ArgumentList $ChromeCleanItems -ErrorAction Stop | ForEach-Object { # 将远程执行的输出写入日志 if ($_ -match "失败") { Write-Log $_ -Level ERROR } else { Write-Log $_ } } Write-Log "计算机$computer处理完成" -Level SUCCESS } catch { Write-Log "计算机$computer远程调用失败:$_" -Level ERROR } } Write-Log "=== 批量缓存清理任务执行完成 ==="
功能说明
- 执行顺序:严格按照「遍历每台目标计算机→遍历该计算机下所有用户目录→对应用户缓存清理」的逻辑执行,完全符合需求
- 日志能力:所有操作都会记录时间、执行状态、详情内容,同时输出到控制台和日志文件,日志文件按执行时间命名,方便回溯
- 错误处理:增加连通性检测、远程调用异常捕获、单步清理异常捕获,任何环节失败都会明确标注错误原因,不会中断整个脚本执行
- 冗余优化:删除了不必要的中间CSV文件,合并了Firefox重复的清理路径,统一管理清理规则,维护成本更低
内容的提问来源于stack exchange,提问作者MjrPayne
相关产品推荐
相关产品推荐

