You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell多PC批量清理用户配置文件脚本功能扩展

多PC远程用户配置文件批量清理脚本整合方案

前置要求

脚本运行前需满足以下条件:

  • 执行脚本的账号拥有所有目标设备的本地管理员权限
  • 目标设备已开启WinRM服务,防火墙放开WMI/WinRM远程访问规则(域环境加域设备默认满足,工作组设备需手动执行winrm quickconfig配置放行)
  • 不要在核心业务服务器上随意开启清理开关,避免配置文件误删

整合后完整脚本

# -------------------------- 配置项 规则与原本地脚本完全一致 --------------------------
$ExcludedUsers = "admin","test"  # 无需清理的排除用户列表
$RunOnServers = $false  # 是否允许在服务器操作系统上执行清理
[int]$MaximumProfileAge = 30  # 清理最后写入时间早于指定天数的配置文件,设为0则清理所有符合条件的配置
$LogSource = "Stone Profile Cleanup"
# -----------------------------------------------------------------------------

# 目标计算机列表加载
Write-Host "请选择目标设备加载方式:"
Write-Host "1. 手动输入计算机名,多个设备用英文逗号分隔"
Write-Host "2. 从文本文件导入,文件内每行填写一个计算机名/IP"
$select = Read-Host "请输入选项序号(1/2)"
$targetComputers = @()

if ($select -eq "1") {
    $inputStr = Read-Host "请输入计算机名列表"
    $targetComputers = $inputStr.Split(",") | ForEach-Object { $_.Trim() } | Where-Object { $_ }
}
elseif ($select -eq "2") {
    $filePath = Read-Host "请输入计算机列表文件的完整路径(例:C:\temp\device_list.txt)"
    if (Test-Path $filePath) {
        $targetComputers = Get-Content $filePath | ForEach-Object { $_.Trim() } | Where-Object { $_ -notmatch "^#" -and $_ }
    }
    else {
        Write-Error "指定的列表文件不存在,脚本退出"
        exit 1
    }
}
else {
    Write-Error "输入选项无效,脚本退出"
    exit 1
}

if (-not $targetComputers) {
    Write-Error "未获取到有效目标设备,脚本退出"
    exit 1
}

# 核心清理逻辑 完全保留原脚本的判断规则
$cleanupScriptBlock = {
    param($ExcludedUsers, $RunOnServers, $MaximumProfileAge, $LogSource)
    $osInfo = Get-CimInstance -ClassName Win32_OperatingSystem
    if ($RunOnServers -eq $true -or $osInfo.ProductType -eq 1) {
        New-EventLog -LogName Application -Source $LogSource -ErrorAction SilentlyContinue
        $profiles = Get-CimInstance -Class Win32_UserProfile | Where-Object {(!$_.Special -and $_.Loaded -eq $false )}
        $removedCount = 0
        foreach ($profile in $profiles) {
            $userName = $profile.LocalPath.Split('\')[-1]
            if ($ExcludedUsers -notcontains $userName) {
                $usrClassPath = Join-Path $profile.LocalPath "AppData\Local\Microsoft\Windows\UsrClass.dat"
                if (Test-Path $usrClassPath) {
                    $lastWriteTime = (Get-Item -Path $usrClassPath -Force).LastWriteTime
                    if ($lastWriteTime -lt (Get-Date).AddDays(-$MaximumProfileAge)) {
                        Remove-CimInstance -InputObject $profile -ErrorAction SilentlyContinue
                        $removedCount++
                    }
                }
            }
        }
        Write-EventLog –LogName Application –Source $LogSource –EntryType Information –EventID 1701 -Category 2 -Message ("配置文件清理完成,共清理$removedCount个留存超过$MaximumProfileAge天的用户配置文件")
        return [PSCustomObject]@{
            ComputerName = $env:COMPUTERNAME
            ExecuteStatus = "成功"
            RemovedCount = $removedCount
        }
    }
    else {
        return [PSCustomObject]@{
            ComputerName = $env:COMPUTERNAME
            ExecuteStatus = "跳过:当前设备为服务器系统,配置禁止在服务器执行清理"
            RemovedCount = 0
        }
    }
}

# 批量执行清理
$executeResult = @()
foreach ($device in $targetComputers) {
    Write-Host "正在处理设备:$device"
    try {
        if ($device -eq $env:COMPUTERNAME -or $device -eq "." -or $device -eq "localhost") {
            # 本地设备直接执行
            $res = & $cleanupScriptBlock -ExcludedUsers $ExcludedUsers -RunOnServers $RunOnServers -MaximumProfileAge $MaximumProfileAge -LogSource $LogSource
        }
        else {
            # 远程设备调用,兼容参考代码的CIM远程调用逻辑
            $res = Invoke-Command -ComputerName $device -ScriptBlock $cleanupScriptBlock -ArgumentList $ExcludedUsers,$RunOnServers,$MaximumProfileAge,$LogSource -ErrorAction Stop
        }
        $executeResult += $res
    }
    catch {
        $executeResult += [PSCustomObject]@{
            ComputerName = $device
            ExecuteStatus = "失败:$($_.Exception.Message)"
            RemovedCount = 0
        }
    }
}

# 输出结果汇总
Write-Host "`n所有任务执行完成,结果汇总:"
$executeResult | Format-Table -AutoSize

主要调整说明

  • 修复原脚本重复定义配置块、变量拼写错误的问题,将原脚本使用的过时WMI命令替换为官方推荐的CIM命令,与提供的远程操作参考代码逻辑完全兼容
  • 新增两种目标设备加载方式,支持手动输入或从文本文件批量导入,自动过滤空行、注释行
  • 核心清理规则100%保留原有逻辑:排除指定用户、跳过特殊账户/已加载配置文件、按UsrClass.dat最后写入时间判断配置文件留存时长、清理记录写入目标设备本地应用程序事件日志
  • 新增异常捕获机制,单台设备连接失败、执行报错不会中断整个批量任务,所有设备处理完成后统一输出执行结果汇总
  • 事件日志内容补充实际清理的配置文件数量,方便后续审计排查

内容的提问来源于stack exchange,提问作者Luminoza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 01:15:32