How to run on-demand AV scanning on a file with MS Defender using Powershell

Last month I published an article on MS Defender and Nagios, on a similar topic this week I used the MS Defender Powershell module and wrote a helper function to scan a file using mpcmd.exe.

mpcmd.exe

As usual, the best place to start is the official documentation for mpcmd.exe.

First of all Microsoft Defender Platform version, run MpCmdRun from the following location: C:\ProgramData\Microsoft\Windows Defender\Platform\<antimalware platform version>.  Then there is a parameter called -Scan [-ScanType [<value>]] [-File <path> ].

Scans for malicious software. Values for ScanType are:

  • 0 Default, according to your configuration
  • 1 Quick scan
  • 2 Full scan
  • 3 File and directory custom scan.

That was and is exactly what I’m looking for.

MS Defender Powershell Module

I won’t repeat what I’ve already covered in the previous article, but this oneliner can be a useful summary of your general status which includes enabled/disabled features and the latest updates for MS Defender.

PS D:\Get-MpComputerStatus | Select-Object AntispywareSignatureLastUpdated, AntivirusSignatureLastUpdated,NISSignatureLastUpdated,AntivirusEnabled,IsTamperProtected,IoavProtectionEnabled,RealTimeProtectionEnabled,OnAccessProtectionEnabled

AntispywareSignatureLastUpdated : 15/07/2021 12:11:48 PM
AntivirusSignatureLastUpdated   : 15/07/2021 12:11:49 PM
NISSignatureLastUpdated         : 15/07/2021 12:11:49 PM
AntivirusEnabled                : True
IsTamperProtected               : True
IoavProtectionEnabled           : True
RealTimeProtectionEnabled       : True
OnAccessProtectionEnabled       : True

My PowerShell script

I’ve started my script with a #requires statement to be sure that the dependency of the defender module is satisfied.
The function has only one parameter called file which is the full path of a file and the input is also validated.
There is also a check of the antivirus definition that would trigger an automatic update if the latest update is older than 2 days.
The return value is a boolean $False (Negative result for the AV Scan) and $True (Positive result for the AV Scan), but if you would like more details you can use the -verbose switch.

#requires -module defender

#Paolo Frigo, https://www.scriptinglibrary.com

<# .Synopsis Wrapper function of the Microsoft Defender on demand scanner feature .DESCRIPTION Wrapper function of the Microsoft Defender on demand scanner feature with a built-in check for AV signature update. .PARAMETER file Full path of the file to scan with the AV .EXAMPLE Get-AVFileScan -file "FULL_PATH_OF_YOUR_FILE" .EXAMPLE Get-AVFileScan -file "FULL_PATH_OF_YOUR_FILE" -verbose #>
function Get-AVFileScan
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
         [ValidateScript({Test-Path $_ })]
         [string]
        $file
    )

    Begin
    {
         if ((Get-MpComputerStatus).AntivirusSignatureLastUpdated -lt $(Get-Date).adddays(-2)) {
            Write-Warning "Your AV definitions are older than 2 days. Launching the Signature Update."
            Update-MpSignature -Verbose
         }
    }
    Process
    {
        $DefenderFolder = (Get-ChildItem "C:\ProgramData\Microsoft\Windows Defender\Platform\" | Sort-Object -Descending | Select-Object -First 1).fullname
        $Defender = "$defenderFolder\MpCmdRun.exe"
        $output = & $Defender -scan -scantype 3 -file (get-item $file).FullName
        $output | ForEach-Object {Write-Verbose $_}

        return $output[-1] -notmatch "no threats"
    }
    End
    {
    }
}

Example of the output

Once imported with dot-sourcing I can call my function and with the verbose switch will see all completed operations and output.

PS D:\Git\scriptinglibrary\Blog\PowerShell> . .\Get-AVFileScan.ps1
PS D:\Git\scriptinglibrary\Blog\PowerShell> Get-AVFileScan -file rdg.xml -verbose
VERBOSE: Scan starting...
VERBOSE: Scan finished.
VERBOSE: Scanning D:\Git\scriptinglibrary\Blog\PowerShell\rdg.xml found no threats.
False

Checking the log

It’s always important to know where to find the logs of your apps. when you use mpcmd.exe, MS Defender creates a log file in the AppData temp folder of the current user.
If you want to tail the last 20 lines you can use this oneliner:

PS D:\get-content -tail -20 ~\appdata\local\temp\MpCmdRun.log

I hope you will find it useful and, as usual, you can find all of these scripts on my GitHub repository.

One Reply to “How to run on-demand AV scanning on a file with MS Defender using Powershell”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.