Как включить windows defender через powershell

Microsoft Defender is a built-in antivirus software that comes pre-installed on all Windows 10 and 11 editions. Users can manage the Microsoft Defender antivirus from the Windows Security app GUI or using the PowerShell command line. This guide explains how to use PowerShell to enable/disable Microsoft Defender on Windows, how to manage various settings, and scan the computer for threats and viruses.

How to Check the Microsoft Defender Status with PowerShell

Only Windows desktop operating systems (such as Windows 11 or 10) have Microsoft Defender antivirus pre-installed. Open an elevated PowerShell prompt and check the current status of Microsoft Defender with the command:

Get-MpComputerStatus

Or quickly check if Microsoft Defender is on, which protection settings are enabled, and when antivirus definitions were last updated:

Get-MpComputerStatus | Select-Object -Property Antivirusenabled,AMServiceEnabled,AntispywareEnabled,BehaviorMonitorEnabled,IoavProtectionEnabled,NISEnabled,OnAccessProtectionEnabled,RealTimeProtectionEnabled,IsTamperProtected,AntivirusSignatureLastUpdated

disable windows defender powershell

If Defender Antivirus is disabled, check the following service statuses on a computer:

  • Microsoft Defender Antivirus Service (WinDefend)
  • Windows Security Service (SecurityHealthService),
  • Security Center (wscsvc)
Get-Service Windefend, SecurityHealthService, wscsvc| Select Name,DisplayName,Status

disable defender powershell

How to Disable or Enable Microsoft Defender Protection using PowerShell

In Windows 10 and 11, you can temporarily pause Microsoft Defender protection or turn it off completely.

How to Temporarily Disable (Pause) the Defender Antivirus Protection on Windows

There is a built-in security feature called Tamper protection that is enabled by default in all modern versions of Windows (starting with build 21H2). This feature prevents users from modifying Defender security features through PowerShell, registry settings, or Group Policy.

Check the Tamper Protection state:

Get-MpComputerStatus | select IsTamperProtected

disable tamper protection powershell

Tamper Protection can only be disabled from the Windows Security UI. Go to “Virus & Threat Protection” > click “Manage Settings” > scroll down to “Tamper Protection” and move the slider to the “Off” position.

restart defender service powershell

Tamper protection is off. Your device may be vulnerable.

powershell disable windows defender

Now disable Microsoft Defender real-time protection with PowerShell:

Set-MpPreference -DisableRealtimeMonitoring $true

Disable the cloud-delivered protection:

Set-MpPreference -MAPSReporting Disabled

enable windows defender powershell

This will suspend antivirus protection in Windows until the next restart.

To restore real-time protection, run:

Set-MpPreference -DisableRealtimeMonitoring $false

Turn on cloud-delivered protection:

Set-MpPreference -MAPSReporting Advanced

Permanently Turn Off Microsoft Defender on Windows 11 or 10

If you have a third-party certified AV solution installed on the computer, Microsoft Defender antivirus will automatically switch to passive EDR or block mode. But in some cases, you may to completely disable Microsoft Defender on a computer without installing third-party AV.

In earlier versions of Windows, the Microsoft Defender Antivirus can be disabled using the GPO option Turn off Windows Defender Antivirus (Computer Configuration > Administrative Templates > Windows Components > Microsoft Defender Antivirus) or with the DisableAntiSpyware = 1 registry parameter. However, these options no longer completely disable Microsoft Defender Antivirus in the latest Windows 10 and 11 builds.

powershell disable defender

The only way to completely disable Microsoft Defender is to restart your computer in Safe Mode and prevent the Defender services from starting.

  1. To boot Windows into the Safe Mode, run:
    bcdedit /set {current} safeboot minimal
    
    shutdown -r -t 0

    disable windows defender windows 11 powershell

  2. Open the Registry Editor (regedit.exe) after booting into Safe Mode
  3. Then open the following registry keys one by one and change the value of the Start registry parameter in each key to 4
  4. Now turn off the Safe Mode Boot mode and restart Windows:
    bcdedit /deletevalue {current} safeboot

    Sign into Windows with your account and check that Microsoft Defender is now disabled.

Registry key Parameter Default Value New value (disable defender)
HKLM\SYSTEM\CurrentControlSet\Services\Sense\ Start 3 4
HKLM\SYSTEM\CurrentControlSet\Services\WdBoot\ Start 0 4
HKLM\SYSTEM\CurrentControlSet\Services\WdFilter\ Start 0 4
HKLM\SYSTEM\CurrentControlSet\Services\WdNisDrv\ Start 3 4
HKLM\SYSTEM\CurrentControlSet\Services\WdNisSvc\ Start 3 4
HKLM\SYSTEM\CurrentControlSet\Services\WinDefend\ Start 2 4

windows defender disable powershell

Uninstall Windows Defender on Windows Server 2019/2016 using PowerShell

Microsoft Defender is not pre-installed by default on Windows Server 2019/2016 platforms. It can be installed as an additional feature:

Install-WindowsFeature -Name Windows-Defender

If you want to uninstall Windows Defender on a Windows Server, remove the feature:

Uninstall-WindowsFeature -Name Windows-Defender

Manage Microsoft Defender Using PowerShell

Microsoft.SecHealthUI is a graphical UWP app that can be used for the management of Microsoft Defender on Windows 10 and 11 (available via Settings > Privacy & Security > Windows Security or with the ms-settings:windowsdefender command).

powershell script to disable windows defender

All of the Microsoft Defender configuration settings that are available in the Windows Security app can be performed using the PowerShell cmdlets of the built-in Defender module. List available cmdlets in this module:

Get-Command -Module Defender

turn off defender powershell

You can get help about a specific cmdlet from the Defender module:

Get-Help Start-MpScan –Full

Or only list examples:

Get-Help Add-MpPreference -Examples

The following are the most common Microsoft Defender management tasks that you can perform from the PowerShell prompt:

Turn certain Microsoft Defender security options on or off

The following Microsoft Defender features are disabled by default:

  • DisableCatchupFullScan.
  • DisableCatchupQuickScan.
  • DisableCpuThrottleOnIdleScans.
  • DisableEmailScanning.
  • DisableRemovableDriveScanning.
  • DisableRestorePoint.
  • DisableScanningMappedNetworkDrivesForFullScan.
  • EnableFileHashComputation.
  • EnableFullScanOnBatteryPower.
  • EnableLowCpuPriority.

For example, enable automatic scanning of removable drives:

Set-MpPreference -DisableRemovableDriveScanning $false

windows defender install powershell

Disable real-time scanning of archive files (files (RAR, ZIP, CAB):

Set-MpPreference -DisableArchiveScanning $True

Enable protect against unwanted programs (Potentially Unwanted Program — PUP, Potentially Unwanted Application — PUA):

Set-MpPreference -PUAProtection 1

Manage Microsoft Defender antivirus exclusions

  • Add paths to the antivirus exclusions:
    Add-MpPreference -ExclusionPath C:\Video, C:\install
  • Remove a folder exclusion:
    Remove-MpPreference -ExclusionPath C:\install
  • Exclude process from real-time antivirus scanning:
    Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe"
  • Exclude specific file extensions from Microsoft Defender scan:
    Set-MpPreference -ExclusionExtension *.mp3,*.MP4,*.wav,*.EDB

Disable Microsoft Defender user interface (UI)

Set-MpPreference -UILockdown $true

‘Virus and threat protection’ section will be hidden from the Windows Security UI.

windows 11 disable defender powershell

Update Microsoft Defender signatures

Update-MpSignature

Update antivirus definitions from a shared network folder on your LAN. Download the necessary definition update files and set an UNC path as the default update source:

Set-MpPreference -SignatureDefinitionUpdateFileSharesSources \\DESKTOP-V20E3PO\Updates

Update the virus and malware definitions:

Update-MpSignature -UpdateSource FileShares

Update-MpSignature

Run an on-demand antivirus scan

Start-MpScan -ScanType CustomScan -ScanPath ”C:\Program Files”

disable defender windows 11 powershell

Perform a full computer scan:

Start-MpScan -ScanType FullScan

Or quick threats scan:

Start-MpScan -ScanType QuickScan

Run an offline scan by booting into an isolated WinPE environment.

Start-MpWDOScan

remove defender powershell

View threat history

Get-MpThreat

List of active and pass malware detections:

Get-MpThreatDetection

disable microsoft defender powershell

To remove all active threats:

Remove-MpThreat

Cyril Kardashevsky

I enjoy technology and developing websites. Since 2012 I’m running a few of my own websites, and share useful content on gadgets, PC administration and website promotion.

Microsoft has invested heavily in Microsoft Defender Antivirus (known as Windows Defender) over the years to reduce the attack surface on the Windows environment against viruses and spyware, and ransomware.

There are multiple ways of managing Windows Defender, such as PowerShell, GPO, UI…etc. In this post, the focus is on managing Windows Defender by using PowerShell. Seems good… so let’s start.

Table of Contents

How to Get Windows Defender Realtime Protection Status using PowerShell

To get Windows Defender’s real-time protection status using PowerShell, you need to:

  1. Open Windows PowerShell, and make sure you start PowerShell as Administrator.
  2. Type the following PowerShell line
Get-MpComputerStatus | select RealTimeProtectionEnabled

The output shows the status of Windows Defender.

Windows Defender status

Windows Defender status

How to get The Defender Status on a Remote Machine using WMI.

To get Windows Defender status on a remote machine, you can use WMI:

  • Open Windows PowerShell, and make sure you start PowerShell as Administrator.
  • Type the following PowerShell line
Get-CimInstance -ComputerName MyRemoteServer -Query 'Select * from MSFT_MPComputerStatus' -Namespace 'root\Microsoft\Windows\Defender' | Select RealTimeProtectionEnabled,PSComputerName

The result shows the current Windows Defender status on the remote server.

Windows Defender status on a remote server using WMI

Windows Defender status on a remote server using WMI

All the Windows Defender WMI classes are located under Root\Microsoft\Windows\Defender namespace.

Disable Windows Defender Using PowerShell.

To turn off or disable Windows Defender using PowerShell, start with the following.

  1. Open Windows PowerShell, and make sure you start PowerShell as Administrator.
  2. Type the following PowerShell line
Set-MpPreference -DisableRealtimeMonitoring $true

No result appears after the execution, but you can confirm that Windows Defender is disabled by running the PowerShell line.

Get-MpPreference | Select-Object DisableRealtimeMonitoring

The Return of the line above will be $True

Windows Defender is disabled

Disabled Windows Defender

Enable Windows Defender Using PowerShell

To turn on or Enable Windows Defender using PowerShell, start with the following.

  1. Open Windows PowerShell, and make sure you start PowerShell as Administrator.
  2. Type the following PowerShell line.
set-MpPreference -DisableRealtimeMonitoring $False
Enabling Windows Defender from PowerShell

Enabling Windows Defender from PowerShell

There will be no result return, but you can confirm that settings are disabled by running the following cmdlet.

Get-MpPreference | Select-Object DisableRealtimeMonitoring

The return of the command line should be $False

Enabling Windows Defender.

Reading the status.

Updating Windows Defender Definitions

Get the Definition Date and Age

Windows Defender requires an internet connection to get the latest signature and antivirus database as with any security solution. So let’s see how to update the definitions online.

Its possible to download the definitions as an offline package, but to utilize the best protection and AI integration with Microsoft cloud, its highly recommended to keep ensure your computer is connected to the internet.

First, let’s get the details of the current definition.

Get-MpComputerStatus | Select-Object *LastUpdated,*SignatureAge
Computer Protection Signature state

Computer Protection Signature state

Using Get-MpComputerStatus lists all the computer protection details, such as last scan time, the scanned score, real-time protection status, etc. But to get the result related to the signature info, use the Select-Object

Look at the dates as it gives the last time the update was completed. Also, the AntispywareSignatureAge, AntivirusSignatureAge, and NISSignatureAge represent the gap between today and the last successful update. So this is a pretty old definition and should be updated as soon as possible.

Its also possible to get the protection details on a remote computer using the following line

Invoke-Command -ScriptBlock {Get-MpComputerStatus} -ComputerName Your_Remote_Server

Update The Signature Definitions Using PowerShell.

To Update the signature definition using PowerShell.

  1. Open Windows PowerShell, and make sure you start PowerShell as Administrator.
  2. In the prompt, type Update-MpSignature

PowerShell will connect to the Microsoft update repo and get the latest definitions. This might take a while and during this process, there is no activity on the screen. It’s not stuck. This is normal.

Windows Defender Signature Update

Signature Update

If the computer is not connected to the internet, you can download an offline copy of the definition from microsoft website

You might see a quick progress bar, but it depends on the internet connection speed.

Windows Defender Update Progress

Update Progress

If the computer is connected to the internet, the Antivirus engine gets its update. There will be no output from the console unless the -Verbose parameter is enabled. The console will return.

VERBOSE: Virus and spyware definitions update was completed successfully.

If the computer is not connected to the internet and PowerShell cannot complete the update, the following error is returned, and you need to get the offline package from the Microsoft website.

Update-MpSignature : Virus and spyware definitions update was completed with errors.

Windows Defender Update failed

Update failed.

How to Update Windows Defender on a Remote Machine using PowerShell

To update windows defender on a remote machine using PowerShell, do the following steps:

  • Open Windows PowerShell, and make sure to start it as Run As Administrator
  • Type the command Update-MPSignature -CimSession RemoteMahcineName
Updating Windows Defender on a remote machine

Updating on a remote machine

How to Start Windows Defender Scan using PowerShell

Before starting the scanning, you need to know the three scanning types available.

  • FullScan: Scan the computer for any threat.
  • QuickScan: Scan System directories, Memory, and common locations.
  • CustomScan: Require to set the ScanPath parameter and type the path to scan

Once you know which scan type is needed, follow the steps below to start the scan you need:

  1. Open Windows PowerShell, and make sure you start PowerShell as Administrator.
  2. Type the following PowerShell line.
#Start Full Scan
Start-MpScan -ScanType FullScan
#Scan Quick Scan
Start-MpScan -ScanType QuickScan
#Scan Custom Scan
Start-MpScan -ScanType CustomScan -ScanPath C:\windows

How to Find the Detected Threat and remove them using PowerShell

To know the history of detected threats using PowerShell:

  1. Open Windows PowerShell, and make sure you Run as Administrator.
  2. Use the command Get-MpThreat
Current detected Threat

Current detected Threat

If you want to test your antivirus functionality and confirm that its able to do a basic detection, then download the Eicar virus test file

To remove the detected threat, follow these steps:

  1. Open Windows PowerShell, and make sure you Run As Administrator
  2. Type the following command Remove-MpThreat
  3. The command has no return unless the -Verbose parameter is set
Remove-MPThreat

Remove-MPThreat command

How to Get all Windows Defender Configuration using PowerShell

To get all the configuration using PowerShell, use the following cmdlet Get-MpPreference.

Take a small break and go through them. You can google any unclear value. But do not worry, as I will take you through some examples and show you how to change these values.


AllowNetworkProtectionOnWinServer             : False
AttackSurfaceReductionOnlyExclusions          : 
AttackSurfaceReductionRules_Actions           : 
AttackSurfaceReductionRules_Ids               : 
CheckForSignaturesBeforeRunningScan           : False
CloudBlockLevel                               : 0
CloudExtendedTimeout                          : 0
ComputerID                                    : 91244B04-B3E5-47DA-AAC2-064CF85D0A1D
ControlledFolderAccessAllowedApplications     : 
ControlledFolderAccessProtectedFolders        : 
DisableArchiveScanning                        : False
DisableAutoExclusions                         : False
DisableBehaviorMonitoring                     : False
DisableBlockAtFirstSeen                       : False
DisableCatchupFullScan                        : True
DisableCatchupQuickScan                       : True
DisableCpuThrottleOnIdleScans                 : True
DisableDatagramProcessing                     : False
DisableEmailScanning                          : True
DisableIntrusionPreventionSystem              : 
DisableIOAVProtection                         : False
DisablePrivacyMode                            : False
DisableRealtimeMonitoring                     : False
DisableRemovableDriveScanning                 : True
DisableRestorePoint                           : True
DisableScanningMappedNetworkDrivesForFullScan : True
DisableScanningNetworkFiles                   : False
DisableScriptScanning                         : False
EnableControlledFolderAccess                  : 0
EnableFileHashComputation                     : False
EnableFullScanOnBatteryPower                  : False
EnableLowCpuPriority                          : False
EnableNetworkProtection                       : 0
ExclusionExtension                            : 
ExclusionIpAddress                            : 
ExclusionPath                                 : 
ExclusionProcess                              : 
ForceUseProxyOnly                             : False
HighThreatDefaultAction                       : 0
LowThreatDefaultAction                        : 0
MAPSReporting                                 : 2
MeteredConnectionUpdates                      : False
ModerateThreatDefaultAction                   : 0
ProxyBypass                                   : 
ProxyPacUrl                                   : 
ProxyServer                                   : 
PUAProtection                                 : 0
QuarantinePurgeItemsAfterDelay                : 90
RandomizeScheduleTaskTimes                    : True
RealTimeScanDirection                         : 0
RemediationScheduleDay                        : 0
RemediationScheduleTime                       : 02:00:00
ReportingAdditionalActionTimeOut              : 10080
ReportingCriticalFailureTimeOut               : 10080
ReportingNonCriticalTimeOut                   : 1440
ScanAvgCPULoadFactor                          : 50
ScanOnlyIfIdleEnabled                         : True
ScanParameters                                : 1
ScanPurgeItemsAfterDelay                      : 15
ScanScheduleDay                               : 0
ScanScheduleQuickScanTime                     : 00:00:00
ScanScheduleTime                              : 02:00:00
SevereThreatDefaultAction                     : 0
SharedSignaturesPath                          : 
SignatureAuGracePeriod                        : 0
SignatureBlobFileSharesSources                : 
SignatureBlobUpdateInterval                   : 60
SignatureDefinitionUpdateFileSharesSources    : 
SignatureDisableUpdateOnStartupWithoutEngine  : False
SignatureFallbackOrder                        : MicrosoftUpdateServer|MMPC
SignatureFirstAuGracePeriod                   : 120
SignatureScheduleDay                          : 8
SignatureScheduleTime                         : 01:45:00
SignatureUpdateCatchupInterval                : 1
SignatureUpdateInterval                       : 0
SubmitSamplesConsent                          : 1
ThreatIDDefaultAction_Actions                 : 
ThreatIDDefaultAction_Ids                     : 
UILockdown                                    : False
UnknownThreatDefaultAction                    : 0
PSComputerName                                : 

How to Disable or Enable Windows Defender Archive (Compressed file) Scanning.

  1. Open Windows PowerShell (Run As Administrator)
  2. Use the Set-MpPreference with DisableArchiveScanning as a parameter
    1. $True: means disable the archive scanning
    2. $False: means don’t disable the archive scanning

So the full command looks like this:

Set-MpPreference -DisableArchiveScanning $true

To confirm the change, you can run the Get-MpPreference

How to Disable or Enable Windows Defender Email scanning using PowerShell.

To disable or enable Windows defender email scanning for incoming and outgoing emails using PowerShell:

  1. Start by opening Windows PowerShell (Run As Administrator)
  2. Use the Set-MpPreference with DisableEmailScanning as a parameter:
    1. :$True: disable the archive scanning.
    2. $False: don’t disable the archive scanning.

So the full command looks like this:

Set-MpPreference -DisableEmailScanning $true
Changing the Email scanning settings

Changing the Email scanning settings

How to Exclude an Extension from Windows Defender Scanning using PowerShell

To exclude an extension from Windows Defender Scanning using PowerShell:

  1. Open PowerShell (Run As Administrator).
  2. Use the Set-MpPreference cmdlet with -ExclusionExtension parameter.
  3. You can add a single or multiple extensions separated by a comma.

So the full command looks like this:

Set-MpPreference -ExclusionExtension *.mp3,*.MP4,*.wav,*.EDB
Disable Extension scanning

Disable Extension scanning

How to Exclude a path from Windows Defender using PowerShell

You can exclude a path or multiple paths from Windows Defender scanning using Powershell using the following steps:

  1. Start Windows PowerShell, and make sure you Run As Administrator.
  2. Use the Set-MpPreference cmdlet with -ExclusionPath parameter.
  3. You can add single or multiple paths separated by a comma.

So the full command looks like this:

Set-MpPreference -ExclusionPath C:\Windows,C:\Users
Excluding Paths from Windows Defender scanning

Excluding Paths from scanning

If the path contain any white space, make sure to include it between quotation mark.

Set-MpPreference -ExclusionPath 'C:\123 abd\'

How to configure Windows Defender Scanning schedule using PowerShell.

The Schedule consists of three elements:

  • Type of Scan (Full or Quick).
  • Time To start the scan.
  • Days of the week to start the scan.

These are the elements you need to understand to create the schedule, so let’s put it all into action.

To configure Windows Defender Scanning Schedule using PowerShell:

  1. Open PowerShell, and make sure you Run As Administrator.
  2. Use the Set-MpPreference with the ScanParameter set to FullScan or QuickScan. So the full command for a full scan looks like Set-MpPreference -ScanParameters FullScan
  3. Let’s configure the starting time. Note that the time is in a 24 Hours format and written as 00:00:00. For example, if the schedule should start at 10 AM, the entire command looks like this:
    Set-MpPreference -ScanScheduleTime 10:00:00
    Another example, If the schedule starts at 11 PM, the entire command looks like this:
    Set-MpPreference -ScanScheduleTime 23:00:00
  4. The last step is to select which day of the week to start the scan on time specified in step two. To set the day, use the parameter. ScanScheduleDay. ScanScheduleDay accepts the following values
    • 0: Everyday
    • 1: Sunday
    • 2: Monday
    • 3: Tuesday
    • 4: Wednesday
    • 5: Thursday
    • 6: Friday
    • 7: Saturday
    • 8: Never

So to enable scanning every day the full command looks like this:
Set-MpPreference -ScanScheduleDay 0 or you can replace the number with the value like
Set-MpPreference -ScanScheduleDay Sunday. Another example, let set the schedule every Monday and Friday, the PowerShell line looks like this:
Set-MpPreference -ScanScheduleDay Monday,Friday

So to put it all together, the following line triggers a full scan on Sunday at 11 PM

Set-MpPreference -ScanScheduleDay Everyday -ScanScheduleTime 23:00:00 -ScanParameters FullScan

Limit Access to Windows Defender UI using PowerShell

To limit access to Windows defender user interface (UI) using PowerShell:

  1. Open Windows PowerShell, and make sure you start PowerShell as Administrator.
  2. Use the Set-MpPreference with UILockdown parameter set to $true, so the full command looks like this:
Set-MpPreference -UILockdown $true

When a user tries to open the application interface, the user will get an error indicating that the Administrator has limited access to this part of the application.

Your IT administrator has limited access to some areas of this app, and the item you tried to access is not available. Contact IT Helpdesk for more information

Windows Defender Antivirus UILock is enabled

Windows Defender Antivirus UILock is enabled.

Also, you will notice that the antivirus icon disappears from the Security Center.

No Antivirus

To gain back access to the antivirus, use the following command

Set-MpPreference -UILockdown $False

This should be effective within a minute.

Read More

I hope you like this post. I think you will enjoy the following post on how to Control your infrastructure using Telegram and PowerShell.

Windows Defender впервые появился как антивирусная утилита от MS еще в Windows XP, и начиная с Windows Vista он постоянно присутствует в операционных системах Windows в качестве встроенного средства защиты от зловредов. В Windows 8 Defender был объединен с другим антивирусным продуктом — Microsoft Security Essentials, так что на данный момент он является полноценным антивирусным решением.

Windows Defender достаточно производителен и не требователен к системным ресурсам, он может быть использован не только на домашних компьютерах, но и в сети небольших организаций. Антивирус можно обновлять как с сайтов Microsoft, так и с внутреннего WSUS сервера. Однако, основным плюсом Windows Defender является тот факт, что он уже предустановлен и активен в Windows, и практически не требует ручной донастройки.

Совет. На данный момент Windows Defender является частью системы только на пользовательских ОС, и не доступен в Windows Server. Однако в предрелизе Windows Server 2016, Windows Defender может быть установлен как отдельный компонент сервера командой:

Install-WindowsFeature-Name Windows-Server-Antimalware

В большинство случае Windows Defender хорошо работает и со стандартными настройками, но в случае необходимости их можно изменить. Большое количество настроек Defender можно изменить через PowerShell с помощью специального модуля Defender. Впервые он появился в PowerShell 4.0 и разработан специально для управления Windows Defender. Этот модуль содержит 11 командлетов.

Полный список командлетов модуля можно вывести с помощью команды:

Get-Command -Module Defender

  • Add-MpPreferenc
  • Get-MpComputerStatus
  • Get-MpPreference
  • Get-MpThreat
  • Get-MpThreatCatalog
  • Get-MpThreatDetection
  • Remove-MpPreference
  • Remove-MpThreat
  • Set-MpPreference
  • Start-MpScan
  • Update-MpSignature

Get-MpComputerStatus – позволяет вывести текущий статус (включенные опции, дату и версию антивирусных баз, время последнего сканирования и т.д.)

Вывести текущие настройки Defender может командлет Get-MpPreference, чтобы их изменить используется — Set-MpPreference.

Например, нам требуется включить сканирование внешних USB накопителей. Получим текущие настройки командой:

Get-MpPreference | fl disable*

Как вы видит сканирование USB накопителей отключено (DisableRemovableDriveScanning = True). Включим сканирование командой:

Set-MpPreference -DisableRemovableDriveScanning $false

Также, чтобы изменить настройки антивируса можно использовать командлеты Add-MpPreference и Remove-MpPreference. Например, добавим несколько папок в список исключений антивируса (сканирование в них не будет выполняться):

Add-MpPreference -ExclusionPath C:\Video, C:\install

Полный список исключений Windows Defender можно вывести так:

Get-MpPreference | fl excl*

Удалим конкретную папку из списка исключений:

Remove-MpPreference -ExclusionPath C:\install

Для обновления антивирусных сигнатур в базе используется команда Update-MpSignature. С помощью аргумента UpdateSource можно указать источник обновлений.

Возможны следующие источники обновлений:

  • MicrosoftUpdateServer – сервера обновлений MS в интернете
  • MMPC — Microsoft Malware Protection Center
  • FileShares – сетевая папка
  • InternalDefinitionUpdateServer — внутренний WSUS сервер

Для обновления из сетевой папки нужно предварительно скачать файлы с сигнатурами баз с сайта https://www.microsoft.com/security/portal/definitions/adl.aspx и поместить в сетевой каталог. Чтобы обновить базы Defender из сетевого каталога, нужно задать его UNC путь:

Set-MpPreference -SignatureDefinitionUpdateFileSharesSources \\FileShare1\Updates

Запустим обновление:

Update-MpSignature -UpdateSource FileShares
Update-MpSignature

Выполнить сканирование системы можно с помощью командлета Start-MpScan. Аргумент ScanType позволяет указать один из трех режимов сканирования.

  • FullScan – полное сканирование всех файлов на компьютере, в том числе реестра и запушенных программ
  • QuickScan – быстрый анализ наиболее частых мест, которые могут быть инфицированы
  • CustomScan – пользователь сам может указать диски и папки для сканирования.

Например, чтобы просканировать каталог “C:\Program Files”:

Start-MpScan -ScanType CustomScan -ScanPath ”C:\Program Files”

Все командлеты модуля Defender могут быть использованы для управления как локальным, так и удаленным компьютером. Для подключения к удаленному компьютеру нужно использовать опцию CimSession. Например, чтобы получить время последнего сканирования на удаленном компьютере с именем msk-wks-1, запустите такую команду (WimRM на удаленном ПК должен быть включен):

$session = NewCimSession -ComputerName msk-wks-1
Get-MpComputerStatus -CimSession $session | fl fullscan*

Если нужно отключить защиту Defender в реальном времени:

Set-MpPreference -DisableRealtimeMonitoring $true

Полностью отключить Windows Defender на компьютере можно, добавив в реестр ключ с помощью команды PowerShell:

New-ItemProperty -Path “HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender” -Name DisableAntiSpyware -Value 1 -PropertyType DWORD -Force

Все способы:

  • Способ 1: Использование других методов открытия
  • Способ 2: Исправление или сброс приложения
  • Способ 3: Установка недостающих пакетов через «PowerShell»
  • Способ 4: Восстановление и переустановка через «PowerShell»
  • Способ 5: Проверка системных обновлений
  • Способ 6: Проверка целостности системных файлов
  • Способ 7: Возвращение Windows 11 к исходному состоянию
  • Вопросы и ответы: 1

Способ 1: Использование других методов открытия

Перед тем как вы перейдете к реализации более сложных методов, позволяющих восстанавливать работу «Защитника Windows» в Виндовс 11, советуем попробовать один из других вариантов открытия классического приложения. Возможно, у вас возникли проблемы только с конкретным методом или не удается найти нужную кнопку, поэтому альтернативные варианты могут оказаться полезными. Детальнее о них читайте в материале по следующей ссылке.

Подробнее: Как открыть Windows Defender в Windows 11

Пропал Windows Defender в Windows 11-01

Способ 2: Исправление или сброс приложения

«Защитник Windows» является классическим приложением и представлен в ОС точно так же, как и другие стандартные программы. Для него тоже поддерживаются настройки и дополнительные параметры, среди которых можно отыскать сброс и исправление. Мы рекомендуем использовать эти инструменты в первую очередь, поскольку от вас требуется просто их запустить.

  1. Откройте «Пуск» и перейдите в «Параметры», кликнув по значку с изображением шестеренки.
  2. Пропал Windows Defender в Windows 11-02

  3. Далее в разделе «Приложения» выберите категорию «Приложения и возможности».
  4. Пропал Windows Defender в Windows 11-03

  5. В списке программ найдите «Безопасность Windows», справа в этой строке кликните по трем точкам для вызова меню, из которого выберите пункт «Дополнительные параметры».
  6. Пропал Windows Defender в Windows 11-04

  7. В блоке «Сбросить» сначала рекомендуем щелкнуть по «Исправить», чтобы запустить автоматический процесс восстановления.
  8. Пропал Windows Defender в Windows 11-05

  9. Если после него вы все еще не видите нужное вам приложение или испытываете трудности с его запуском, нажмите «Сброс», а по завершении повторите попытку перейти к стандартному антивирусу.
  10. Пропал Windows Defender в Windows 11-06

Способ 3: Установка недостающих пакетов через «PowerShell»

Этот вариант следует попробовать, если при выполнении предыдущего вы даже не нашли приложение с названием «Безопасность Windows». Это может означать, что оно просто отсутствует в операционной системе или файлы являются поврежденными. Для установки недостающих компонентов понадобится воспользоваться «PowerShell». Только учитывайте, что вместе с Защитником будут добавлены и пакеты других стандартных программ, отсутствующих в вашей сборке или удаленных вручную.

  1. Щелкните правой кнопкой мыши по «Пуску» и из появившегося контекстного меню выберите пункт «Терминал Windows (Администратор)».
  2. Введите команду Set-ExecutionPolicy Unrestricted для получения списка недостающих пакетов.
  3. Пропал Windows Defender в Windows 11-08

  4. После ее выполнения используйте Get-AppXPackage -AllUsers | Foreach {Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppXManifest.xml"} и нажмите Enter для применения.
  5. Пропал Windows Defender в Windows 11-09

  6. Начнется процесс поиска и инсталляции файлов. Это может занять много времени, что зависит от количества отсутствующих пакетов и скорости вашего интернета. Как только вы увидите сообщение об успехе, попробуйте перезагрузить ПК и снова поискать Windows Defender на вашем компьютере.
  7. Пропал Windows Defender в Windows 11-010

Способ 4: Восстановление и переустановка через «PowerShell»

Следующий метод снова подразумевает использование консоли, но на этот раз команда будет всего одна и предназначена она исключительно для работы с «Защитником Windows». Она проверит его файлы, а при их отсутствии произведет повторную установку, что часто позволяет наладить работу стандартного компонента.

  1. Обязательно запускайте «Терминал Windows» от имени администратора, как это было показано в предыдущей инструкции.
  2. Введите команду Get-AppxPackage Microsoft.SecHealthUI-AllUsers | Reset-AppxPackage и нажмите Enter для ее применения.
  3. Пропал Windows Defender в Windows 11-012

  4. Через несколько секунд на экране должна появиться новая строка ввода. Это означает, что операция уже завершена, а вы можете переходить к проверке работы «Безопасности Windows».
  5. Пропал Windows Defender в Windows 11-013

Способ 5: Проверка системных обновлений

Сейчас очень активно выходят обновления для Windows 11, особенно это относится к различным апдейтам KB, связанным с безопасностью. Определенные из них вносят исправления в работу «Защитника Windows», что может вернуть компонент и наладить его запуск конкретно в вашем случае. Понадобится найти системные и необязательные обновления, затем произвести их инсталляцию.

  1. В «Параметрах» выберите раздел «Центр обновления Windows» и запустите процесс поиска апдейтов.
  2. Пропал Windows Defender в Windows 11-014

  3. Параллельно с этим можете перейти к просмотру необязательных обновлений, среди которых тоже могут быть патчи безопасности.
  4. Пропал Windows Defender в Windows 11-015

  5. Щелкните по списку «Необязательные обновления» для его открытия. Если апдейты будут найдены, отметьте их галочками и подтвердите инсталляцию (обновления драйверов в этом случае можно пропустить).
  6. Пропал Windows Defender в Windows 11-016

Способ 6: Проверка целостности системных файлов

Нередко причиной отсутствия или неудачного запуска «Защитника Windows» становятся поврежденные или отсутствующие системные файлы. Если ничего из перечисленного выше не помогло вам решить ситуацию, рекомендуем запустить системные утилиты, которые как раз и предназначены для сканирования и исправления подобных проблем. Детально о них рассказывает другой наш автор в своей статье по следующей ссылке.

Подробнее: Использование и восстановление проверки целостности системных файлов в Windows

Пропал Windows Defender в Windows 11-017

Способ 7: Возвращение Windows 11 к исходному состоянию

Прибегать к реализации этого метода стоит в тех случаях, когда при помощи предыдущих вам так и не удалось вернуть «Защитник Windows» в операционную систему. Возможно, его установка изначально прошла неуспешно по каким-то причинам или вы используете пиратскую сборку ОС, где компонент просто отсутствует. Можете попробовать выполнить переустановку путем возвращения Виндовс к исходному состоянию. Для этого не нужны специальные программы, обойтись можно штатным средством.

Подробнее: Сброс Windows 11 к заводским настройкам

Пропал Windows Defender в Windows 11-018

Наша группа в TelegramПолезные советы и помощь

Windows Defender is an antivirus that is built into the Windows operating system. Here this tutorial on MiniTool will walk you through how to manage Windows Defender with PowerShell command line. You will learn how to check the antivirus status, run a quick/full scan, enable/disable the real-time protection, etc. with Windows Defender PowerShell commands.

Overview of Windows Defender and PowerShell

Windows Defender is the default antivirus software on Windows developed by Microsoft. It is used to scan your computer for viruses, malware, or other threats and then remove them to protect your device. PowerShell is a tool used to manage computer tasks. For example, you can use PowerShell to empty the Recycle Bin, use PowerShell to check if a file exists, and more.

In this article, we will show you how to manage Windows Defender with PowerShell. Keep reading to get specific command lines.

How to Manage Windows Defender With PowerShell

Check Whether Windows Defender Is Enabled

First, we will show you how to check the current status of Windows Defender by using PowerShell.

Step 1. In the Windows search box, type PowerShell and then select Run as administrator under Windows PowerShell in the right pane.

Step 2. If a UAC window appears, click the Yes option to continue.

Step 3. In the command line window, type Get-MpComputerStatus and press Enter.

Step 4. In the new window, if the value of AntivirusEnabled is True, it means that the Windows Defender antivirus is running. If the AntivirusEnabled status shows as False, it indicates that Windows Defender is disabled.

AntivirusEnabled status

Enable/Disable Windows Defender Real-time Protection PowerShell

After executing the above command line, in addition to the status of Windows Defender, a lot of other information about this antivirus software will be displayed, including the real-time protection status.

If the real-time protection is disabled and you want to enable it, you can run this command line:

Set-MpPreference -DisableRealtimeMonitoring $false

The command line to disable Windows Defender antivirus real-time protection is:

Set-MpPreference -DisableRealtimeMonitoring $true

Run a Quick Scan/Full Scan/Custom Scan/Offline Scan

Here you can see how to perform a quick/full/custom/offline scan by using Windows Defender PowerShell commands.

Quick scan:

Type this command: Start-MpScan -ScanType QuickScan in the command line window and press Enter. Then a quick scan will start.

Full scan:

To carry out a full virus scan, you need to execute this command line: Start-MpScan -ScanType FullScan.

Custom scan:

Windows Defender allows you to select specific drives or locations to check for viruses. Here you can see how to complete this task via PowerShell.

First, confirm the location/drive you want to scan.

Second, type Start-MpScan -ScanType CustomScan -ScanPath file location path and press Enter. You need to replace the file location path with the actual directory. For example, you can type Start-MpScan -ScanType CustomScan -ScanPath C:\Users\username\Documents and press Enter to scan the Documents folder. Remember to replace the username with the actual one.

run the command to scan the Documents folder for viruses

Offline scan:

Windows Defender provides you with an offline scan option that helps you detect and remove persistent malware or viruses. This scan runs outside of the Windows kernel so it can inspect and clean your system more thoroughly.

Tips:

Before running the command line to perform an offline scan, you need to make sure all your open works are saved. Running an offline scan requires a computer restart.

Input Start-MpWDOScan and press Enter to start scanning for viruses offline.

This is all about how to manage Windows Defender with PowerShell.

Windows Data Recovery Software Recommended:

There are many cases of data loss due to virus infection. Some viruses can directly delete files on your computer while others may damage the hard drive file system, making the files inaccessible or unreadable. If you encounter such a situation and lose your files, you can use MiniTool Power Data Recovery to recover deleted files.

The free edition of this data recovery software supports recovering 1 GB of documents, pictures, videos, audio, emails, etc. for free. You can download it and have a try.

MiniTool Power Data Recovery FreeClick to Download100%Clean & Safe

Bottom Line

How to manage Windows Defender with PowerShell? Now you should know the command lines to check Windows Defender status, enable/disable real-time protection, and run different types of virus scans.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Автоматическая очистка реестра windows 10
  • Монтирование линукс дисков в windows
  • Некоторыми из этих параметров управляет ваша организация windows 11 буфер обмена
  • Аналог macbook pro на windows
  • Windows 10 не видит kindle