如何编写系统封装辅助脚本

wen 实用脚本 3

本文目录导读:

如何编写系统封装辅助脚本

  1. 基础脚本框架
  2. 核心功能模块
  3. 执行Sysprep命令
  4. 完整脚本结构
  5. 使用建议

我来为您介绍如何编写系统封装辅助脚本(Sysprep辅助脚本),这将帮助您自动化Windows系统封装过程。

基础脚本框架

Windows Batch脚本

@echo off系统封装辅助工具
color 0A
setlocal enabledelayedexpansion
:: 获取当前时间
set datetime=%date:~0,4%%date:~5,2%%date:~8,2%_%time:~0,2%%time:~3,2%%time:~6,2%
set datetime=%datetime: =0%
:: 日志文件
set LOGFILE=C:\Sysprep\Logs\sysprep_%datetime%.log
mkdir C:\Sysprep\Logs 2>nul
:: 日志函数
call :WriteLog "=== 系统封装开始 ==="

PowerShell脚本

# 系统封装辅助脚本
$ScriptVersion = "1.0"
$LogPath = "C:\Sysprep\Logs"
$LogFile = Join-Path $LogPath "sysprep_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
# 创建日志目录
New-Item -ItemType Directory -Path $LogPath -Force | Out-Null
# 日志函数
Function Write-Log {
    param([string]$Message)
    $Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $LogEntry = "$Timestamp - $Message"
    Write-Host $LogEntry -ForegroundColor Green
    Add-Content -Path $LogFile -Value $LogEntry
}

核心功能模块

1 清理模块

:Cleanup
call :WriteLog "开始清理系统..."
:: 清理临时文件
del /f /q %WINDIR%\Temp\*.* 2>nul
del /f /q %TEMP%\*.* 2>nul
:: 清理日志
wevtutil cl Application
wevtutil cl System
wevtutil cl Security
:: 清理用户历史
del /f /s /q %USERPROFILE%\Recent\*.* 2>nul
del /f /s /q %USERPROFILE%\AppData\Local\Microsoft\Windows\History\*.* 2>nul
:: 清理缓存
ipconfig /flushdns
Function Invoke-SystemCleanup {
    Write-Log "开始清理系统..."
    # 清理临时文件
    $tempPaths = @(
        "$env:WINDIR\Temp",
        "$env:TEMP",
        "$env:USERPROFILE\AppData\Local\Temp"
    )
    foreach ($path in $tempPaths) {
        if (Test-Path $path) {
            Remove-Item "$path\*" -Recurse -Force -ErrorAction SilentlyContinue
            Write-Log "已清理: $path"
        }
    }
    # 清理事件日志
    wevtutil cl Application
    wevtutil cl System
    wevtutil cl Security
}

2 配置优化模块

:OptimizeSettings
call :WriteLog "优化系统设置..."
:: 关闭系统还原
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" /v DisableSR /t REG_DWORD /d 1 /f
:: 关闭休眠
powercfg -h off
:: 设置电源计划为高性能
powercfg -setactive SCHEME_MIN
:: 关闭Windows Defender实时保护
reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows Defender" /v DisableAntiSpyware /t REG_DWORD /d 1 /f
:: 禁用自动更新
sc config wuauserv start= disabled
net stop wuauserv
Function Optimize-SystemSettings {
    Write-Log "优化系统设置..."
    # 系统还原设置
    Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" `
        -Name "DisableSR" -Value 1 -Type DWord
    # 电源设置
    powercfg -h off
    powercfg -setactive SCHEME_MIN
    # 服务配置
    $servicesToDisable = @(
        @{Name="wuauserv"; Display="Windows Update"},
        @{Name="SysMain"; Display="Superfetch"},
        @{Name="DiagTrack"; Display="Connected User Experiences and Telemetry"}
    )
    foreach ($service in $servicesToDisable) {
        Set-Service -Name $service.Name -StartupType Disabled
        Stop-Service -Name $service.Name -Force -ErrorAction SilentlyContinue
        Write-Log "已禁用服务: $($service.Display)"
    }
}

3 系统准备模块

:PrepareSystem
call :WriteLog "准备系统封装..."
:: 删除特定用户账户(除Administrator和Default Users)
net user | findstr /V "Administrator DefaultAccount Guest" | findstr /R "^[A-Za-z]" > temp_users.txt
for /f "tokens=1" %%u in (temp_users.txt) do (
    net user %%u /delete
    call :WriteLog "已删除用户: %%u"
)
del temp_users.txt
:: 清理用户配置文件
del /f /s /q "C:\Users\*\NTUSER.DAT.LOG*" 2>nul
:: 重置网络设置
netsh int ip reset
netsh winsock reset
:: 清理驱动程序
pnputil -e | findstr /C:"Published Name" > drivers.txt
Function Prepare-System {
    Write-Log "准备系统封装..."
    # 用户管理
    $usersToDelete = Get-LocalUser | Where-Object {
        $_.Name -notin @('Administrator', 'DefaultAccount', 'Guest')
    }
    foreach ($user in $usersToDelete) {
        Remove-LocalUser -Name $user.Name -ErrorAction SilentlyContinue
        Write-Log "已删除用户: $($user.Name)"
    }
    # 网络重置
    netsh int ip reset
    netsh winsock reset
    # 清理注册表
    $regPaths = @(
        "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Setup\Sysprep\Cleanup",
        "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
    )
    # 自定义清理逻辑
}

执行Sysprep命令

:ExecuteSysprep
call :WriteLog "执行系统封装..."
set SYSPREP_PATH=C:\Windows\System32\Sysprep
set SYSPREP_EXE=%SYSPREP_PATH%\sysprep.exe
:: 配置Sysprep参数
set SYSPREP_MODE=oobe
set SYSPREP_SHUTDOWN=shutdown
set SYSPREP_GENERALIZE=/generalize
set SYSPREP_QUIET=/quiet
:: 备份Sysprep日志
if exist %SYSPREP_PATH%\Panther\setupact.log (
    copy %SYSPREP_PATH%\Panther\setupact.log C:\Sysprep\Logs\sysprep_setup.log
)
:: 执行Sysprep
call :WriteLog "正在执行Sysprep,请勿关闭计算机..."
%SYSPREP_EXE% /%SYSPREP_MODE% /%SYSPREP_SHUTDOWN% %SYSPREP_GENERALIZE% %SYSPREP_QUIET%
Function Invoke-SysprepExecution {
    Write-Log "执行系统封装..."
    $SysprepPath = "C:\Windows\System32\Sysprep"
    $SysprepExe = Join-Path $SysprepPath "sysprep.exe"
    # 配置参数
    $params = @(
        "/oobe",
        "/shutdown",
        "/generalize",
        "/quiet"
    )
    # 备份日志
    $logSource = Join-Path $SysprepPath "Panther\setupact.log"
    if (Test-Path $logSource) {
        Copy-Item $logSource -Destination "C:\Sysprep\Logs\sysprep_setup.log"
    }
    # 执行Sysprep
    Write-Log "正在执行Sysprep,请勿关闭计算机..."
    Start-Process -FilePath $SysprepExe -ArgumentList $params -Wait -NoNewWindow
}

完整脚本结构

Batch版本(完整)

@echo off系统封装辅助工具 v1.0
color 0A
setlocal enabledelayedexpansion
:: 初始化
set LOGDIR=C:\Sysprep\Logs
mkdir %LOGDIR% 2>nul
set datetime=%date:~0,4%%date:~5,2%%date:~8,2%_%time:~0,2%%time:~3,2%%time:~6,2%
set datetime=%datetime: =0%
set LOGFILE=%LOGDIR%\sysprep_%datetime%.log
:: 主程序
call :WriteLog "=== 系统封装工具启动 ==="
call :CheckAdmin
call :Cleanup
call :OptimizeSettings
call :PrepareSystem
call :PromptSysprep
call :WriteLog "=== 封装准备完成 ==="
goto :EOF
:CheckAdmin
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo 请以管理员身份运行此脚本!
    pause
    exit /b 1
)
goto :EOF
:WriteLog
echo [%date% %time%] %*>> %LOGFILE%
echo %*
exit /b 0
:PromptSysprep
echo.
echo ================================================
echo 系统封装准备已完成!
echo.
echo 是否立即执行Sysprep?
echo 1. 是 - 立即执行系统封装
echo 2. 否 - 退出程序,稍后手动执行
echo ================================================
set /p choice="请选择 (1/2): "
if "%choice%"=="1" call :ExecuteSysprep
if "%choice%"=="2" exit /b 0
goto :EOF
:ExecuteSysprep
call :WriteLog "开始执行Sysprep..."
C:\Windows\System32\Sysprep\sysprep.exe /oobe /shutdown /generalize /quiet
goto :EOF

PowerShell版本(完整)

# 系统封装辅助工具
[CmdletBinding()]
param(
    [switch]$AutoMode,
    [switch]$NoSysprep
)
$ScriptVersion = "1.0"
$LogPath = "C:\Sysprep\Logs"
$LogFile = Join-Path $LogPath "sysprep_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
# 创建目录
New-Item -ItemType Directory -Path $LogPath -Force | Out-Null
# 日志函数
Function Write-Log {
    param([string]$Message, [string]$Level = "INFO")
    $Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $LogEntry = "$Timestamp [$Level] - $Message"
    switch ($Level) {
        "ERROR" { Write-Host $LogEntry -ForegroundColor Red }
        "WARN"  { Write-Host $LogEntry -ForegroundColor Yellow }
        "SUCCESS" { Write-Host $LogEntry -ForegroundColor Green }
        default { Write-Host $LogEntry -ForegroundColor Cyan }
    }
    Add-Content -Path $LogFile -Value $LogEntry
}
# 检查管理员权限
Function Test-AdminPrivilege {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($identity)
    return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
# 主程序
try {
    Write-Log "=== 系统封装辅助工具 v$ScriptVersion ==="
    # 权限检查
    if (-not (Test-AdminPrivilege)) {
        Write-Log "请以管理员身份运行此脚本!" -Level "ERROR"
        exit 1
    }
    # 执行各个模块
    Invoke-SystemCleanup
    Optimize-SystemSettings
    Prepare-System
    Write-Log "=== 封装准备完成 ===" -Level "SUCCESS"
    # 询问是否执行Sysprep
    if (-not $NoSysprep) {
        if ($AutoMode) {
            Invoke-SysprepExecution
        } else {
            $response = Read-Host "是否立即执行Sysprep? (Y/N)"
            if ($response -eq 'Y' -or $response -eq 'y') {
                Invoke-SysprepExecution
            }
        }
    }
} catch {
    Write-Log "脚本执行出错: $_" -Level "ERROR"
    exit 1
}

使用建议

部署注意事项

  1. 测试环境:先在测试环境验证脚本
  2. 备份数据:执行前备份重要数据
  3. 日志检查:执行后检查日志文件
  4. 兼容性:确保脚本与目标系统版本兼容

扩展功能建议

  • 集成驱动程序安装
  • 自定义应用部署
  • 网络配置模板
  • 安全策略配置
  • 系统激活处理

这个脚本框架提供了一个完整的系统封装辅助解决方案,您可以根据实际需求进行修改和扩展。

抱歉,评论功能暂时关闭!