How to fix Error 5065 on Windows Server 2025 / Windows 11

Troubleshooting Guide: SQL Server Error 5065 – File Currently Being Scanned or Used

Why This Error Happens

Error 5065 occurs when SQL Server attempts to perform a file-level operation (such as a database file move, shrink, or offline operation) while the target file is locked by an external process like antivirus real-time scanning, Windows Search Indexer, or a backup agent. This is particularly common on Windows Server 2025 and Windows 11 due to enhanced Microsoft Defender behavioral scanning, which aggressively hooks into file handles for .mdf, .ndf, and .ldf files. Because SQL Server cannot obtain an exclusive lock on the file while the third-party process holds a handle open, the operation is rejected rather than queued.

Step-by-Step Resolution Guide

Step 1: Identify the Process Locking the File

  • Open Resource Monitor (resmon.exe) and navigate to the CPU tab, then use Associated Handles.
  • Search for the specific .mdf/.ldf file path mentioned in the error message.
  • Alternatively, use Sysinternals handle.exe from an elevated Command Prompt: handle.exe "D:\SQLData\YourDB.mdf".

Step 2: Exclude SQL Server Directories from Antivirus/Defender Scanning

  • Open Windows Security > Virus & threat protection > Manage settings > Exclusions.
  • Add folder exclusions for your SQL data, log, and backup directories (e.g., D:\SQLData\, D:\SQLLogs\, E:\SQLBackups\).
  • Also exclude the SQL Server executable: C:\Program Files\Microsoft SQL Server\MSSQL17.MSSQLSERVER\MSSQL\Binn\sqlservr.exe.
  • Restart the Windows Defender Antivirus Service via services.msc to apply changes immediately.

Step 3: Disable Windows Search Indexing on SQL Volumes

  • Open File Explorer, right-click the drive containing your SQL files (e.g., D:\), and select Properties.
  • Uncheck “Allow files on this drive to have contents indexed…” and apply changes to subfolders.
  • Confirm the Windows Search service (WSearch) is set to Disabled on dedicated SQL Server instances via services.msc.

Step 4: Retry the Operation with SQL Server Isolated

  • Stop any third-party backup agents (e.g., Veeam, Commvault) that may be triggering VSS snapshots on the volume.
  • Re-run the failed command (e.g., ALTER DATABASE ... MODIFY FILE or DBCC SHRINKFILE) from SSMS.
  • If the error persists, restart the SQL Server (MSSQLSERVER) service during a maintenance window to release any stale file handles.

Alternative or Verification Steps

  • Verify the fix by re-running the original T-SQL command that triggered Error 5065; it should complete without the “file is currently being scanned” message.
  • If the issue reoccurs intermittently, check Task Scheduler for scheduled antivirus “Quick Scans” that may overlap with SQL Server maintenance windows, and reschedule them to non-peak hours.