How to Run a Memory Diagnostic (memtest) in Batch Script
Random Blue Screen of Death (BSOD) errors with varying stop codes, application crashes with memory-related errors, system freezes, and file system corruption that recurs after repair, these are classic symptoms of faulty RAM. Windows includes a built-in Memory Diagnostic tool (mdsched.exe) that performs thorough read/write tests on all installed memory. A Batch script can schedule the diagnostic, manage the reboot, and retrieve the results afterward, creating a complete hardware troubleshooting workflow.
This guide explains how to automate memory testing and result retrieval.
How the Memory Diagnostic Works
-
Normal Boot:
- BIOS → Bootloader → Windows
-
Diagnostic Boot (after mdsched scheduling):
- BIOS → Memory Diagnostic Tool → Tests ALL RAM → Results saved → Windows boots
The Memory Diagnostic cannot run while Windows is active, it needs exclusive access to every byte of RAM. When you "run" the diagnostic, you actually schedule it for the next boot. The BIOS hands control to the diagnostic tool instead of Windows, the tool tests all memory, saves results to a system event, then boots Windows normally.
Running mdsched.exe does NOT perform the test immediately. It schedules the test for the next reboot. The actual testing takes 15–60 minutes after restart, depending on RAM size and test mode. Results are only available after Windows boots back up.
Test modes:
| Mode | Duration (8 GB RAM) | What It Tests | Best For |
|---|---|---|---|
| Basic | ~5 minutes | Simple patterns, address checks | Quick pass/fail |
| Standard (default) | ~15 minutes | All Basic tests + more patterns | Most situations |
| Extended | ~45–90 minutes | All Standard tests + aggressive bit patterns | Intermittent errors that occur rarely |
Press F1 during the pre-boot test screen to change between modes.
Method 1: Schedule Memory Diagnostic with Reboot Option
This method schedules the diagnostic, offers an immediate or deferred reboot, and provides a companion script to retrieve results.
Schedule Script
@echo off
setlocal
echo ============================================================
echo Memory Diagnostic Scheduler
echo ============================================================
echo.
:: Check admin rights (scheduling requires elevation)
net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Scheduling a memory diagnostic requires administrator privileges. >&2
echo Right-click and select "Run as administrator." >&2
endlocal
exit /b 1
)
:: Check if a diagnostic is already scheduled
:: mdsched stores its schedule in the BCD - check for the entry
bcdedit /enum {memdiag} >nul 2>&1
if not errorlevel 1 (
echo [INFO] A memory diagnostic may already be scheduled.
echo [INFO] If you recently ran one, results may be available.
echo.
echo [TIP] Check results with:
echo powershell -Command "Get-WinEvent -ProviderName 'Microsoft-Windows-MemoryDiagnostics-Results' -MaxEvents 1"
echo.
)
:: Provide context about what will happen
echo [INFO] The Windows Memory Diagnostic will:
echo 1. Schedule a memory test for the next restart
echo 2. Test ALL installed RAM (the test runs before Windows loads^)
echo 3. Take 15-60 minutes depending on RAM size and test mode
echo 4. Boot Windows normally when finished
echo 5. Save results to the Windows Event Log
echo.
echo [WARNING] The computer will restart to perform the test.
echo Save all open work before proceeding.
echo.
set /p "Confirm=Schedule the memory diagnostic? (YES/no): "
if /i not "%Confirm%"=="YES" (
echo [INFO] Cancelled.
endlocal
exit /b 0
)
echo.
:: Schedule the diagnostic
:: mdsched.exe with no arguments opens the GUI dialog
:: We'll use it to schedule and offer immediate restart
echo [ACTION] Launching Memory Diagnostic scheduler...
:: Method A: Direct GUI (user chooses restart timing)
mdsched.exe
echo.
echo [INFO] If you chose "Restart now," the computer will reboot shortly.
echo [INFO] If you chose "Check next time," the test runs on the next manual restart.
echo.
echo [AFTER THE TEST] Run the results checker:
echo %~dp0check_memory_results.bat
echo.
echo ============================================================
endlocal
exit /b 0
Results Retrieval Script (check_memory_results.bat)
@echo off
setlocal
echo ============================================================
echo Memory Diagnostic Results
echo ============================================================
echo.
:: Query the Memory Diagnostics Results event
echo [INFO] Searching for memory diagnostic results...
echo.
powershell -NoProfile -Command ^
"$events = Get-WinEvent -ProviderName 'Microsoft-Windows-MemoryDiagnostics-Results' -MaxEvents 5 -ErrorAction SilentlyContinue;" ^
"if (-not $events) {" ^
" Write-Host 'No memory diagnostic results found.';" ^
" Write-Host '';" ^
" Write-Host 'This means either:';" ^
" Write-Host ' - No diagnostic has been run on this machine';" ^
" Write-Host ' - The diagnostic was scheduled but the computer has not been restarted yet';" ^
" Write-Host ' - The results were cleared from the Event Log';" ^
" exit 1" ^
"};" ^
"Write-Host 'Most recent diagnostic results:';" ^
"Write-Host '';" ^
"$events | ForEach-Object {" ^
" Write-Host \" Date: $($_.TimeCreated.ToString('yyyy-MM-dd HH:mm:ss'))\";" ^
" Write-Host \" Result: $($_.Message)\";" ^
" Write-Host ''" ^
"};" ^
"$latest = $events[0].Message;" ^
"if ($latest -match 'no errors') {" ^
" Write-Host '[OK] The most recent test found NO memory errors.';" ^
" Write-Host ' RAM appears to be functioning correctly.'" ^
"} elseif ($latest -match 'hardware problems') {" ^
" Write-Host '[ALERT] The test detected MEMORY ERRORS!';" ^
" Write-Host ' One or more RAM modules may be faulty.';" ^
" Write-Host '';" ^
" Write-Host ' Recommended actions:';" ^
" Write-Host ' 1. Note which DIMM slots are populated';" ^
" Write-Host ' 2. Remove all but one RAM stick';" ^
" Write-Host ' 3. Run the diagnostic again';" ^
" Write-Host ' 4. Repeat with each stick to identify the faulty module';" ^
" Write-Host ' 5. Replace the faulty module';" ^
" exit 2" ^
"} else {" ^
" Write-Host '[INFO] Result message does not match known patterns.';" ^
" Write-Host ' Review the message above for details.'" ^
"}"
set "DiagResult=%errorlevel%"
echo.
echo ============================================================
endlocal
exit /b %DiagResult%
Exit codes for automation:
| Exit Code | Meaning |
|---|---|
0 | No errors found, RAM is healthy |
1 | No diagnostic results available |
2 | Memory errors detected, faulty RAM |
Why results appear in the Event Log:
The Memory Diagnostic runs before Windows loads. It can't display results during the test (it shows only a progress screen). Instead, it writes the results to a special location that Windows reads on the next boot and converts into an Event Log entry under the provider Microsoft-Windows-MemoryDiagnostics-Results.
After the diagnostic completes and Windows boots, the results event may take a minute or two to appear in the Event Log. If the results script shows "No results found" immediately after booting, wait a few minutes and try again.
Method 2: Silent Scheduling (No GUI)
For remote management or automated maintenance scripts where the interactive mdsched.exe dialog is not appropriate.
@echo off
setlocal
echo [ACTION] Scheduling memory diagnostic (silent mode^)...
net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Administrator privileges required. >&2
endlocal
exit /b 1
)
:: Schedule the diagnostic using bcdedit to set the boot entry
:: This is the mechanism mdsched.exe uses internally
bcdedit /bootsequence {memdiag} /addfirst >nul 2>&1
if not errorlevel 1 (
echo [OK] Memory diagnostic scheduled for next reboot.
echo.
echo [INFO] On the next restart:
echo - The memory test will run automatically (no user interaction^)
echo - Default test mode is "Standard" (press F1 during test to change^)
echo - Test takes 15-60 minutes depending on RAM size
echo - Windows boots normally after the test completes
echo.
echo [INFO] After the test, retrieve results with:
echo powershell -Command "Get-WinEvent -ProviderName 'Microsoft-Windows-MemoryDiagnostics-Results' -MaxEvents 1"
) else (
echo [ERROR] Failed to schedule diagnostic. >&2
echo [INFO] Try using mdsched.exe directly instead. >&2
endlocal
exit /b 1
)
echo.
set /p "Reboot=Reboot now to start the test? (YES/no): "
if /i "%Reboot%"=="YES" (
echo [ACTION] Rebooting in 15 seconds...
echo [WARNING] Save all work - the test begins immediately after restart.
shutdown /r /t 15 /c "Memory Diagnostic - restarting for RAM test."
)
endlocal
exit /b 0
How bcdedit /bootsequence {memdiag} works:
The {memdiag} boot entry is always present in the BCD but is normally not in the boot sequence. Adding it with /bootsequence /addfirst tells the bootloader to start the memory diagnostic BEFORE Windows on the next boot only. After the diagnostic completes, the boot sequence reverts to normal, Windows boots normally on all subsequent restarts without the diagnostic.
mdsched.exe provides a GUI that asks "Restart now or later?" and handles the scheduling internally. bcdedit /bootsequence {memdiag} /addfirst achieves the same result silently, no GUI appears. Use mdsched.exe for interactive use and bcdedit for automated/remote scheduling.
Method 3: Complete RAM Troubleshooting Workflow
When a system is experiencing stability issues that may be RAM-related, this method provides a structured diagnostic workflow: check for symptoms, run the diagnostic, retrieve and interpret results.
@echo off
setlocal EnableDelayedExpansion
echo ============================================================
echo RAM Health Assessment
echo ============================================================
echo.
:: =============================================
:: Phase 1: Check for RAM-related symptoms
:: =============================================
echo [1/3] Checking for RAM-related indicators...
echo.
:: Check for recent BSODs
set "BSODCount=0"
for /f "usebackq delims=" %%n in (
`powershell -NoProfile -Command ^
"$crashes = Get-WinEvent -FilterHashtable @{" ^
" LogName='System';" ^
" ProviderName='Microsoft-Windows-Kernel-Power';" ^
" Id=41;" ^
" StartTime=(Get-Date).AddDays(-30)" ^
"} -ErrorAction SilentlyContinue;" ^
"if ($crashes) { $crashes.Count } else { 0 }"`
) do set "BSODCount=%%n"
echo BSODs in last 30 days: %BSODCount%
:: Check for memory-related BSOD stop codes in the Event Log
set "MemBSODs=0"
for /f "usebackq delims=" %%n in (
`powershell -NoProfile -Command ^
"$events = Get-WinEvent -FilterHashtable @{" ^
" LogName='System';" ^
" Id=1001;" ^
" StartTime=(Get-Date).AddDays(-30)" ^
"} -ErrorAction SilentlyContinue;" ^
"if ($events) {" ^
" ($events | Where-Object { $_.Message -match '0x0000000A|0x0000001E|0x00000050|0x0000007F|0x000000F2' }).Count" ^
"} else { 0 }"`
) do set "MemBSODs=%%n"
echo Memory-related stop codes: %MemBSODs%
:: Check installed RAM
for /f "usebackq delims=" %%r in (
`powershell -NoProfile -Command ^
"$ram = (Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory;" ^
"[math]::Round($ram / 1GB, 1)"`
) do echo Installed RAM: %%r GB
:: Check for previous diagnostic results
for /f "usebackq delims=" %%d in (
`powershell -NoProfile -Command ^
"$result = Get-WinEvent -ProviderName 'Microsoft-Windows-MemoryDiagnostics-Results' -MaxEvents 1 -ErrorAction SilentlyContinue;" ^
"if ($result) { $result.TimeCreated.ToString('yyyy-MM-dd') } else { 'Never' }"`
) do echo Last diagnostic: %%d
echo.
:: =============================================
:: Phase 2: Recommend action
:: =============================================
echo [2/3] Assessment:
echo.
set "ShouldTest=FALSE"
if %BSODCount% gtr 0 (
echo [!] %BSODCount% BSOD(s^) detected - memory test recommended.
set "ShouldTest=TRUE"
)
if %MemBSODs% gtr 0 (
echo [!] %MemBSODs% memory-related stop code(s^) - strong indicator of RAM issues.
set "ShouldTest=TRUE"
)
if "!ShouldTest!"=="FALSE" (
echo [OK] No obvious RAM-related symptoms detected.
echo A diagnostic test is optional but can rule out subtle issues.
)
echo.
:: =============================================
:: Phase 3: Offer to schedule the diagnostic
:: =============================================
echo [3/3] Schedule memory diagnostic?
echo.
set /p "RunTest=Schedule the memory diagnostic for next reboot? (YES/no): "
if /i not "!RunTest!"=="YES" (
echo [INFO] Diagnostic not scheduled.
endlocal
exit /b 0
)
net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Administrator privileges required to schedule. >&2
echo Re-run as administrator. >&2
endlocal
exit /b 1
)
bcdedit /bootsequence {memdiag} /addfirst >nul 2>&1
if not errorlevel 1 (
echo [OK] Memory diagnostic scheduled for next reboot.
) else (
echo [ERROR] Scheduling failed. Try mdsched.exe manually. >&2
endlocal
exit /b 1
)
echo.
set /p "Reboot=Reboot now to start the test? (YES/no): "
if /i "!Reboot!"=="YES" (
shutdown /r /t 15 /c "Memory Diagnostic - restarting for RAM test."
)
endlocal
exit /b 0
Memory-related BSOD stop codes:
| Stop Code | Name | RAM Connection |
|---|---|---|
0x0000000A | IRQL_NOT_LESS_OR_EQUAL | Bad memory address access - often faulty RAM |
0x0000001E | KMODE_EXCEPTION_NOT_HANDLED | Memory exception - could be driver or RAM |
0x00000050 | PAGE_FAULT_IN_NONPAGED_AREA | Accessing invalid memory page - strong RAM indicator |
0x0000007F | UNEXPECTED_KERNEL_MODE_TRAP | Double fault - often caused by defective memory |
0x000000F2 | HARDWARE_INTERRUPT_STORM | Hardware interrupt flood - may indicate failing RAM controller |
These codes don't GUARANTEE a RAM problem (they can also be caused by drivers), but when they appear repeatedly with different modules involved, RAM is the most likely culprit.
How to Avoid Common Errors
Wrong Way: Expecting Immediate Results
mdsched.exe
:: (Looking for results in Event Viewer immediately)
:: Result: "No events found" - because the test hasn't run yet!
mdsched.exe only SCHEDULES the test. Results appear in the Event Log only after the computer has rebooted, the test has run (15–60 minutes), and Windows has booted back up.
Correct Way: Schedule → Reboot → Wait for test to complete → Boot Windows → Check Event Log (Method 1's results script).
Wrong Way: Interrupting the Test
The diagnostic test screen shows a progress bar that may appear stuck at certain percentages. Users sometimes force-restart the computer thinking it's frozen. Interrupting the test can (rarely) cause boot configuration issues.
Correct Way: Let the test complete. It may take up to 90 minutes with Extended mode on 32+ GB of RAM. The progress bar updates infrequently during certain test phases.
Problem: Results Say "No Errors" But System Still Crashes
The Standard test mode catches most RAM failures but may miss intermittent issues. RAM that passes Standard can still fail Extended.
Solution: Press F1 during the diagnostic pre-boot screen and select "Extended" for a more thorough test. Additionally, consider running the test multiple passes (configurable via F1 menu) or using the third-party tool MemTest86 for the most comprehensive testing.
The built-in Windows tool (mdsched.exe) is convenient, schedulable from Batch, no bootable USB needed. However, MemTest86 (free, downloadable) provides:
- More test patterns and algorithms
- Specific identification of which address range is failing
- Multi-pass testing with configurable parameters
- Detailed technical reports
Use mdsched.exe for initial screening and MemTest86 for deep investigation when mdsched passes but you still suspect RAM.
Problem: Computer Won't Boot After Diagnostic
In rare cases, the diagnostic entry in the BCD may prevent normal booting (boot loops back into diagnostic). This usually indicates the diagnostic itself detected a critical error.
Solution: Boot from Windows installation media → Repair → Command Prompt:
bcdedit /deletevalue {memdiag} bootsequence
Or simply let the diagnostic complete, it automatically removes itself from the boot sequence after one run.
Best Practices and Rules
1. Run the Extended Test for Intermittent Issues
Standard mode catches ~95% of RAM failures. For systems that crash only every few days, Extended mode with multiple passes catches the remaining subtle errors.
2. Test One Stick at a Time to Isolate Faulty RAM
The diagnostic reports "errors found" or "no errors" for the entire system. It doesn't identify which DIMM is bad. Remove all but one stick and re-run the test for each stick individually.
3. Check BIOS Memory Settings
Sometimes the issue isn't faulty RAM but incorrect settings. Verify in BIOS:
- XMP/DOCP profile matches the RAM's rated speed
- Memory voltage matches manufacturer specification
- Memory timing settings are correct (or set to "Auto")
4. Pair with BSOD Analysis
Before running the memory diagnostic, check which BSOD stop codes have been occurring (Method 3 does this automatically). Memory-related stop codes strongly suggest RAM testing is the right next step.
5. Schedule via bcdedit for Remote/Automated Use
mdsched.exe opens a GUI dialog. For remote management or automated maintenance, use bcdedit /bootsequence {memdiag} /addfirst (Method 2) to schedule silently.
6. Always Check Results After the Test
The diagnostic doesn't display results on-screen. Users often run the test, see it complete, and assume everything is fine, without actually checking the Event Log. Always run the results script (Method 1) after the test.
Conclusion
The Windows Memory Diagnostic is the first-line tool for testing RAM health, schedulable from Batch, requiring no bootable media, and integrated with the Windows Event Log for result retrieval. By combining pre-test symptom analysis (BSOD stop code checking), silent scheduling (bcdedit), and automated result interpretation (Event Log querying), you create a complete RAM troubleshooting workflow. For intermittent issues, use Extended mode. For deeper analysis, escalate to MemTest86. And always remember: the test runs at the NEXT reboot, not immediately.