Skip to main content

How to Run System File Checker (SFC /scannow) in Batch Script

The System File Checker (SFC) is a built-in Windows utility that scans for and restores corrupted system files. Automating this with a Batch script allows routine system maintenance, remote troubleshooting, and fleet-wide integrity checking. By wrapping sfc /scannow in a script with prerequisite checks, DISM pre-repair, logging, and result analysis, you create a reliable one-click repair utility.

This guide explains how to build a comprehensive system file repair script.

How SFC Works

SFC compares current system files against the "known-good" versions stored in the Windows Component Store (the WinSxS folder). When it finds a mismatch or corruption, it replaces the damaged file with a healthy copy from the store.

  • SFC Repair Flow:
    • Scan all protected system files

    • Compare each file against the Component Store

    • If a mismatch is found:

      • Replace the file from the Component Store (if it is healthy)
      • Report “unable to fix” if the Component Store is also corrupt
    • Log all actions to CBS.log

Administrative Privileges Required

SFC cannot run from a standard user session. It requires full administrative rights to access protected directories and modify system files. Without elevation, the command exits immediately with an error.

The DISM dependency:

SFC uses the Component Store as its repair source. If the Component Store itself is corrupted, SFC finds problems but cannot fix them: it reports "found corrupt files but was unable to fix some of them." Running DISM first repairs the Component Store, ensuring SFC has healthy source files to work with.

  • Correct order:

      1. DISM /RestoreHealth → Repairs the Component Store (the "source")
      1. SFC /scannow → Repairs system files (using the repaired source)

Method 1: Complete System File Repair Utility

This script performs the full repair workflow: admin check, DISM Component Store repair, SFC scan, result analysis, and log extraction.

Implementation

@echo off
setlocal EnableDelayedExpansion

echo ============================================================
echo System File Repair Utility
echo ============================================================
echo.

:: =============================================
:: Step 1: Check for administrative privileges
:: =============================================
net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] This script must be run as Administrator. >&2
echo Right-click and select "Run as administrator." >&2
endlocal
exit /b 1
)

echo [OK] Running with administrator privileges.
echo.

:: =============================================
:: Step 2: DISM - Repair the Component Store
:: =============================================
echo [1/3] Checking Component Store health with DISM...
echo [INFO] This ensures SFC has clean source files for repairs.
echo.

:: First, check health (fast)
dism /online /cleanup-image /checkhealth

echo.

:: If check reports issues, run the full repair
dism /online /cleanup-image /checkhealth 2>&1 | findstr /i "repairable" >nul 2>&1
if not errorlevel 1 (
echo [INFO] Component Store issues detected. Running repair...
echo [INFO] This requires internet access and may take 10-20 minutes.
echo.

dism /online /cleanup-image /restorehealth

if errorlevel 1 (
echo.
echo [WARNING] DISM repair encountered errors. >&2
echo SFC may not be able to fix all issues. >&2
echo.
echo Options: >&2
echo - Ensure internet connectivity (DISM downloads from Windows Update^) >&2
echo - Try with a Windows installation ISO as source: >&2
echo dism /online /cleanup-image /restorehealth /source:D:\sources\install.wim >&2
echo.
) else (
echo [OK] Component Store repaired successfully.
)
) else (
echo [OK] Component Store is healthy. No DISM repair needed.
)

echo.

:: =============================================
:: Step 3: SFC - Scan and repair system files
:: =============================================
echo [2/3] Starting System File Checker scan...
echo [INFO] This scans all protected system files and may take 10-30 minutes.
echo [INFO] Do not close this window or restart the computer during the scan.
echo.

sfc /scannow
set "SFCResult=!errorlevel!"

echo.

:: =============================================
:: Step 4: Analyze results
:: =============================================
echo [3/3] Analyzing results...
echo.

if %SFCResult% equ 0 (
echo [OK] No integrity violations found.
echo Windows system files are healthy.
) else (
echo [INFO] SFC scan completed with result code: %SFCResult%
echo.

:: Check SFC output from the CBS log for specific results
:: SFC logs all actions to CBS.log - parse for the summary
set "FoundCorruption=FALSE"
set "FixedAll=FALSE"

findstr /i /c:"found corrupt files and successfully repaired" "%SystemRoot%\Logs\CBS\CBS.log" >nul 2>&1
if not errorlevel 1 (
echo [OK] Corrupted files were found and REPAIRED successfully.
set "FoundCorruption=TRUE"
set "FixedAll=TRUE"
)

findstr /i /c:"found corrupt files but was unable to fix" "%SystemRoot%\Logs\CBS\CBS.log" >nul 2>&1
if not errorlevel 1 (
echo [WARNING] Corrupted files were found but COULD NOT be repaired. >&2
echo.
echo Next steps: >&2
echo 1. Run DISM /restorehealth with a Windows ISO as source >&2
echo 2. Re-run this script >&2
echo 3. If still failing, check CBS.log for specific files >&2
set "FoundCorruption=TRUE"
set "FixedAll=FALSE"
)

if "!FoundCorruption!"=="FALSE" (
echo [INFO] No specific corruption information found in CBS log.
echo The scan may have encountered an operational error.
)
)

echo.

:: =============================================
:: Offer to extract SFC details from CBS.log
:: =============================================
echo --------------------------------------------------
echo.

set /p "ExtractLog=Extract SFC repair details to a file? (YES/no): "
if /i "!ExtractLog!"=="YES" (
set "DetailFile=%~dp0SFC_Details_%COMPUTERNAME%.txt"

(
echo SFC Scan Details for %COMPUTERNAME%
echo Generated: %date% %time%
echo ==========================================
echo.
) > "!DetailFile!"

findstr /c:"[SR]" "%SystemRoot%\Logs\CBS\CBS.log" >> "!DetailFile!" 2>nul

echo [OK] SFC details saved to: !DetailFile!
echo Open this file to see which specific files were scanned/repaired.
)

echo.
echo ============================================================
echo Maintenance complete.
echo ============================================================

:: Check if a reboot may be needed
if "!FoundCorruption!"=="TRUE" (
echo.
echo [INFO] If repairs were made to files currently in use,
echo a reboot may be required to finalize them.
)

endlocal
exit /b 0

Understanding what the CBS.log extraction shows:

The [SR] prefix in CBS.log marks System Resource entries from SFC. The extracted file shows:

  • Which files were scanned
  • Which files were found corrupt
  • Which files were successfully repaired
  • Which files could not be repaired (and why)

This is the detailed diagnostic information that a technician needs to investigate unresolved issues.

Pending Repairs May Require a Reboot

If SFC repairs files that are currently loaded by the operating system (DLLs, drivers, core services), it stages the replacement. The actual swap happens during the next boot, before Windows fully loads. The script output or CBS.log will indicate: "Repairs will take effect after the next reboot."

Method 2: Quick Health Check (No Repair)

For routine monitoring check if system files are intact without attempting repairs. This is faster and useful for scheduled health audits.

@echo off
setlocal

net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Administrator privileges required. >&2
endlocal
exit /b 1
)

echo [INFO] Running quick system file integrity check...
echo [INFO] This verifies files but does NOT repair them.
echo.

sfc /verifyonly

set "Result=%errorlevel%"

echo.

if %Result% equ 0 (
echo [OK] All system files are intact.
) else (
echo [WARNING] Integrity issues detected. >&2
echo Run the full repair script (Method 1^) to fix them. >&2
)

endlocal
exit /b %Result%

sfc /verifyonly vs. sfc /scannow:

CommandScans Files?Repairs Files?SpeedUse Case
sfc /verifyonlyYesNoFasterHealth checks, scheduled audits
sfc /scannowYesYesSlowerActual repair operations

Scheduling regular health checks:

Run Method 2 as a weekly scheduled task. If it reports issues (non-zero exit code), trigger Method 1 for repair, either automatically or by alerting an administrator.

Method 3: Fleet-Wide SFC Status Report

For IT administrators managing multiple machines, collect SFC health status from each machine to a central CSV.

@echo off
setlocal

set "CSVFile=\\Server\Audit\sfc_health.csv"

net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Administrator privileges required. >&2
endlocal
exit /b 1
)

if not exist "%CSVFile%" (
echo "Timestamp","Computer","SFCResult","Status" > "%CSVFile%" 2>nul
)

echo [INFO] Running system file verification for fleet report...

sfc /verifyonly >nul 2>&1
set "Result=%errorlevel%"

set "Status=Healthy"
if %Result% neq 0 set "Status=Issues Detected"

for /f "delims=" %%t in (
'powershell -NoProfile -Command "Get-Date -Format ''yyyy-MM-dd HH:mm:ss''"'
) do echo "%%t","%COMPUTERNAME%","%Result%","%Status%" >> "%CSVFile%" 2>nul

echo [OK] SFC status exported: %Status%

endlocal
exit /b %Result%

What to look for in the fleet CSV:

  • Status = "Issues Detected": These machines need the full repair (Method 1) run.
  • Same machine reporting issues repeatedly: May indicate a deeper problem, hardware failure (bad RAM corrupting files), persistent malware, or a failing Windows Update installation.
  • All machines suddenly unhealthy: May indicate a bad Windows Update affecting system files fleet-wide.

How to Avoid Common Errors

Wrong Way: Running SFC Without DISM First

:: SFC alone on a system with a corrupted Component Store
sfc /scannow
:: Result: "found corrupt files but was unable to fix some of them"

SFC uses the Component Store as its repair source. If the Component Store is corrupt, SFC finds problems but can't fix them, it has no healthy source to copy from.

Correct Way: Always run dism /online /cleanup-image /restorehealth before sfc /scannow. Method 1 integrates this automatically.

Wrong Way: Running SFC and Immediately Closing the Window

SFC modifies system files. Interrupting it mid-operation can leave files in a partially replaced state, potentially worse than the original corruption.

Correct Way: Let the scan complete fully. Inform the user not to close the window (Method 1 includes this message). If interrupted, re-run the complete scan.

Problem: DISM RestoreHealth Fails Without Internet

dism /restorehealth downloads healthy Component Store files from Windows Update. Without internet access, it fails.

Solution: Provide a Windows installation ISO as an offline repair source:

dism /online /cleanup-image /restorehealth /source:D:\sources\install.wim

Replace D: with the drive letter of the mounted ISO.

Problem: SFC Reports "Cannot Repair" After Multiple Attempts

If both DISM and SFC have been run multiple times and files still can't be repaired, the issue may be:

  • Bad RAM: Corrupted memory can damage files as they're written. Run mdsched.exe (Windows Memory Diagnostic).
  • Failing disk: Bad sectors corrupt files. Check disk health (see our guide on checking disk health with S.M.A.R.T.).
  • Active malware: Malware may be re-corrupting files after SFC repairs them. Run a full antivirus scan.
SFC Cannot Fix Everything

SFC repairs Windows system files only, it cannot fix application files, user data, or driver files from third-party vendors. If system file corruption is caused by hardware failure (bad RAM, failing disk), SFC repairs will be temporary, the hardware will re-corrupt the files. Address the root cause alongside the SFC repair.

Problem: CBS.log Is Very Large

The CBS.log file can grow to hundreds of megabytes. Opening it directly in Notepad is slow or impossible.

Solution: Extract only the SFC-related entries:

findstr /c:"[SR]" "%SystemRoot%\Logs\CBS\CBS.log" > "%~dp0sfc_entries.txt"

This produces a much smaller file containing only the System Resource (SFC) entries.

Best Practices and Rules

1. Always Run DISM Before SFC

DISM repairs the source, SFC repairs the system files. Running them in the correct order (DISM first, then SFC) maximizes the chance of successful repair.

2. Don't Interrupt the Scan

SFC scans take 10–30 minutes. Closing the window or restarting during the scan can leave system files in a partially replaced state.

3. Extract CBS.log for Diagnostics

When SFC reports issues it cannot fix, the CBS.log contains the specific filenames and error codes. Use findstr /c:"[SR]" to extract the relevant entries.

4. Schedule Regular Verification

Run sfc /verifyonly (Method 2) weekly as a scheduled task. This detects corruption early, before it causes application crashes or system instability.

5. Investigate Recurring Corruption

If SFC repeatedly finds and repairs the same files, the root cause is not file corruption but something that is actively corrupting files, typically bad RAM, a failing disk, or malware. Fix the hardware/security issue first.

6. Ensure Power Stability

SFC on a laptop should only run when plugged into power. A battery-dead laptop during a system file replacement can render Windows unbootable.

Conclusion

Integrating sfc /scannow into a Batch script transforms a manual troubleshooting step into a reliable maintenance tool. By running DISM first to ensure a healthy Component Store, analyzing SFC's results with specific error detection, extracting detailed logs for diagnostics, and providing fleet-wide health reporting, you create a comprehensive system integrity management workflow. This approach is particularly effective for managing multiple Windows machines where consistent system health is essential.