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

Last month I’ve 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 on-demand 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.

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.

Example of the output

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

Checking the log

It’s always important knowing 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:

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.