[Feature Request] Button in Config/Fixes that runs a full virus scan with Defender

Open
#4,943 4 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
55/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Active
Tech stack
powershell
Domain
security, tooling

Research direction

Start in winutil.ps1 and inspect the Config/Fixes UI entry points for how buttons and PowerShell actions are wired. Review the proposed Defender scan functions and their documented prerequisites before deciding how each action fits the existing flow. Done means the supported scan action is exposed in the UI, handles unavailable or unsupported systems, and leaves the scan result or failure visible to the user.

Written by the indexing model from the issue text.

Description

new feature
💡 Describe the solution you'd like

This would be a very convenient button to add.

Since I'm not familiar with neither PowerShell programming nor WinUtil's coding style, I sent the latest winutil.ps1 to Claude and asked it to create a code snippet that would cover this feature, while following MS documentation wherever possible.

One button does an online full scan of the system, the other schedules an offline scan, before windows boots up.
I can see the latter one not being accepted, as admittedly it's a bit cumbersome, but the former would be very much appreciated.

function Invoke-WPFDefenderScan {
    <#

    .SYNOPSIS
        Runs a full Microsoft Defender Antivirus scan in a separate PowerShell window

    .DESCRIPTION
        1. Resolves the absolute path of MpCmdRun.exe
        2. Opens a new PowerShell window that updates the virus definitions and then runs
           a full scan (-ScanType 2)

        A full scan can take several hours. Running it inside WinUtil would hold the shared
        process lock for that whole time and block every other button, so the scan is handed
        to its own window instead. It keeps running if WinUtil is closed, and MpCmdRun writes
        its own output there. The window is started with -NoExit so the result stays readable
        after the scan finishes.

        Microsoft documents MpCmdRun.exe at %ProgramFiles%\Windows Defender\MpCmdRun.exe, and
        instructs that on machines running an updated antimalware platform it be run from
        C:\ProgramData\Microsoft\Windows Defender\Platform\<platform version> instead, which is
        where the newest copy of the tool lives. This function follows that instruction: it
        prefers the highest platform version present and falls back to the inbox copy.

        A full scan covers every file on every fixed drive. It does not cover removable drives,
        network files, or mapped network drives, because Microsoft ships those three scanning
        options disabled by default. Enabling them is a separate policy decision, so this
        function deliberately leaves the configured scan scope alone.

        MpCmdRun.exe command reference, including the tool's location:
        https://learn.microsoft.com/defender-endpoint/command-line-arguments-microsoft-defender-antivirus

        Scanning options and their default values:
        https://learn.microsoft.com/defender-endpoint/configure-advanced-scan-types-microsoft-defender-antivirus

        WOW64 environment variables, for why ProgramW6432 is preferred over ProgramFiles:
        https://learn.microsoft.com/windows/win32/winprog64/wow64-implementation-details

    #>

    # WOW64 points ProgramFiles at the (x86) folder inside a 32-bit process, and that folder
    # holds no Windows Defender directory. ProgramW6432 always carries the native path, and
    # only goes missing on 32-bit Windows, where ProgramFiles is already correct.
    $programFiles = if ($env:ProgramW6432) { $env:ProgramW6432 } else { $env:ProgramFiles }

    # Platform updates relocate MpCmdRun.exe out of the inbox folder, so prefer the newest
    # platform build when one is present and fall back to the inbox copy otherwise
    $mpCmdRun = Join-Path $programFiles "Windows Defender\MpCmdRun.exe"
    $platformRoot = Join-Path $env:ProgramData "Microsoft\Windows Defender\Platform"

    if (Test-Path $platformRoot) {
        # Folders are named after the platform version, such as 4.18.25010.11-0. Order by the
        # parsed version rather than by timestamp, since a stale folder can be touched later
        $latestPlatform = Get-ChildItem -Path $platformRoot -Directory -ErrorAction SilentlyContinue |
            Where-Object {
                (($_.Name -split "-")[0] -as [version]) -and (Test-Path (Join-Path $_.FullName "MpCmdRun.exe"))
            } |
            Sort-Object -Property @{ Expression = { [version]($_.Name -split "-")[0] } } -Descending |
            Select-Object -First 1

        if ($latestPlatform) {
            $mpCmdRun = Join-Path $latestPlatform.FullName "MpCmdRun.exe"
        }
    }

    if (-not (Test-Path $mpCmdRun)) {
        $msg = "Microsoft Defender Antivirus was not found on this system, so the scan cannot be started."
        [System.Windows.MessageBox]::Show($msg, "Winutil", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Warning)
        return
    }

    # The path is escaped for the single-quoted call operator, so a folder name that somehow
    # contains a quote cannot break out of the string and run as code
    $escapedPath = $mpCmdRun.Replace("'", "''")
    $command = "& '$escapedPath' -SignatureUpdate; & '$escapedPath' -Scan -ScanType 2"

    # WinUtil already runs elevated, so the child window inherits elevation without a second
    # UAC prompt. -NoExit leaves the window open once MpCmdRun is done.
    Start-Process -FilePath "powershell.exe" -ArgumentList "-NoExit", "-Command", $command

    Write-Host "Using $mpCmdRun"
    Write-Host "===========================================" -ForegroundColor Green
    Write-Host "---  Full scan started in a new window  ---" -ForegroundColor Green
    Write-Host "--- It can take several hours to finish ---" -ForegroundColor Green
    Write-Host "---   Closing WinUtil will not stop it  ---" -ForegroundColor Green
    Write-Host "---  Results appear in Windows Security ---" -ForegroundColor Green
    Write-Host "---       under Protection history      ---" -ForegroundColor Green
    Write-Host "===========================================" -ForegroundColor Green
}
function Invoke-WPFDefenderOfflineScan {
    <#

    .SYNOPSIS
        Schedules a Microsoft Defender Offline scan and restarts the computer

    .DESCRIPTION
        Microsoft Defender Offline boots the machine into a trusted environment and scans
        from outside the normal Windows kernel, which is how it reaches firmware threats
        and rootkits that infect or overwrite the master boot record. A running Windows
        session cannot do this, so the feature requires a restart.

        1. Rejects platforms Microsoft documents as unsupported (ARM Windows, Server SKUs)
        2. Asks the user to confirm, since the machine reboots almost immediately
        3. Updates the virus definitions so the offline scan uses current signatures
        4. Schedules the offline scan and lets Windows restart into it

        Microsoft supports three ways to start this scan: the Windows Security app, WMI,
        and the Start-MpWDOScan cmdlet used here.

        Two documented prerequisites are surfaced to the user rather than changed on their
        behalf. The Windows Recovery Environment must be enabled, otherwise the scan simply
        does not run after the reboot and Windows reports no error at all. BitLocker on the
        system drive should be suspended first, or the recovery key may be requested when
        the machine restarts into the offline environment.

        Results land in Windows Security under Virus & threat protection > Scan options >
        Protection history. Event ID 2030 in the Microsoft-Windows-Windows Defender/Operational
        log confirms the scan was configured to run on the next reboot.

        Microsoft Defender Offline scan, including prerequisites and results:
        https://learn.microsoft.com/defender-endpoint/microsoft-defender-offline

        Start-MpWDOScan reference:
        https://learn.microsoft.com/powershell/module/defender/start-mpwdoscan

        Update-MpSignature reference:
        https://learn.microsoft.com/powershell/module/defender/update-mpsignature

        Win32_OperatingSystem class, for the ProductType values used to detect a Server SKU:
        https://learn.microsoft.com/windows/win32/cimwin32prov/win32-operatingsystem

        WOW64 environment variables, for why PROCESSOR_ARCHITEW6432 is checked as well:
        https://learn.microsoft.com/windows/win32/winprog64/wow64-implementation-details

    #>

    if ($sync.ProcessRunning) {
        $msg = "[Invoke-WPFDefenderOfflineScan] Another process is currently running."
        [System.Windows.MessageBox]::Show($msg, "Winutil", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Warning)
        return
    }

    # Defender Offline does not apply to ARM builds of Windows or to Windows Server SKUs,
    # so stop here instead of restarting the machine for a scan that will never run.
    # ProductType 1 is a workstation. If the query fails, assume workstation rather than
    # blocking the feature, since a null result would otherwise compare as "not 1".
    # WOW64 reports PROCESSOR_ARCHITECTURE as x86 inside a 32-bit process and moves the real
    # architecture into PROCESSOR_ARCHITEW6432, so an ARM64 machine would otherwise slip through
    $architecture = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
    $isArm = $architecture -like "ARM*"
    $productType = (Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue).ProductType
    $isServer = ($null -ne $productType) -and ($productType -ne 1)

    if ($isArm -or $isServer) {
        $unsupported = if ($isArm) { "ARM builds of Windows" } else { "Windows Server" }
        $msg = "Microsoft Defender Offline is not supported on $unsupported. Use the full antivirus scan instead."
        [System.Windows.MessageBox]::Show($msg, "Winutil", [System.Windows.MessageBoxButton]::OK, [System.Windows.MessageBoxImage]::Warning)
        return
    }

    # The offline scan cannot run inside a live Windows session, so confirm before rebooting
    $confirmation = "This will RESTART your computer to run a Microsoft Defender Offline scan.`n`n" +
        "Save your work and close your programs first. The scan runs before Windows loads and takes about 15 minutes, then the machine restarts again.`n`n" +
        "Before continuing, check two things:`n" +
        "- The Windows Recovery Environment must be enabled, or the scan silently does nothing. Verify with: reagentc /info`n" +
        "- If BitLocker protects your system drive, suspend it first, or you may be asked for your recovery key on restart.`n`n" +
        "Do you want to continue?"
    $answer = [System.Windows.MessageBox]::Show($confirmation, "Winutil", [System.Windows.MessageBoxButton]::YesNo, [System.Windows.MessageBoxImage]::Warning)

    if ($answer -ne [System.Windows.MessageBoxResult]::Yes) {
        Write-Host "Defender Offline scan cancelled by the user."
        return
    }

    Invoke-WPFRunspace -ScriptBlock {
        $sync.ProcessRunning = $true
        Invoke-WPFUIThread -ScriptBlock { Set-WinUtilTaskbaritem -state "Indeterminate" -value 0.01 -overlay "logo" }

        # A failed definition update is not a reason to skip the scan, so warn and carry on
        try {
            Write-Host "Updating virus definitions..."
            Update-MpSignature -ErrorAction Stop
        } catch {
            Write-Host "Could not update the definitions: $($_.Exception.Message)"
            Write-Host "Continuing with the signatures already on disk."
        }

        try {
            Write-Host "Scheduling the Defender Offline scan. The computer will restart shortly."
            Start-MpWDOScan -ErrorAction Stop
        } catch {
            # Fails when Defender is in passive mode behind another antivirus, or is blocked by policy
            $sync.ProcessRunning = $false
            Invoke-WPFUIThread -ScriptBlock { Set-WinUtilTaskbaritem -state "Error" -value 1 -overlay "warning" }

            Write-Host "===========================================" -ForegroundColor Red
            Write-Host "---   Could not start the offline scan  ---" -ForegroundColor Red
            Write-Host "===========================================" -ForegroundColor Red
            Write-Host $_.Exception.Message -ForegroundColor Red
            return
        }

        $sync.ProcessRunning = $false
        Invoke-WPFUIThread -ScriptBlock { Set-WinUtilTaskbaritem -state "None" -overlay "checkmark" }

        Write-Host "===========================================" -ForegroundColor Green
        Write-Host "---        Offline scan scheduled       ---" -ForegroundColor Green
        Write-Host "---  After the restart, results appear  ---" -ForegroundColor Green
        Write-Host "---      in Windows Security, under     ---" -ForegroundColor Green
        Write-Host "---          Protection history         ---" -ForegroundColor Green
        Write-Host "===========================================" -ForegroundColor Green
    }
}
Dominant language
PowerShell
Stars
67.2k
Forks
4k
Avg merge
2d 7h
Merged PRs (30d)
11

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from ChrisTitusTech/winutil

All issues in ChrisTitusTech/winutil

Similar issues

More Security issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.