$username='domain\serviceAccount'
$password='PasswordHere'
$encryptedPassword=ConvertTo-SecureString $password -AsPlainText -Force
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName,$encryptedPassword;
$computerNames=@(
'SERVER01',
'SERVER02'
)
function uninstallWindefender{
[bool]$success=$false
$windefendExists=try{Get-service Windefend -ea stop}catch{$false}
if(!$windefendExists){
write-host "Windows Defender is NOT detected on $env:computername"
return $true
}
$computerRole=switch ((Get-CimInstance -ClassName Win32_OperatingSystem).ProductType){
1 {'client'} # ClientOs
2 {'domaincontroller'} #ServerOs with DC role
3 {'memberserver'} #ServerOs machines
}
write-host "$env:computername is detected as a $computerRole."
if($computerRole -in 'domaincontroller','memberserver' -and $windefendExists){
try{
$null=Remove-WindowsFeature Windows-Defender -EA Stop
write-host "Windows Defender has been uninstalled. A reboot is now required on $env:computername to complete the process."
$success=$true
}catch{
write-warning $_
$success=$false
}
}elseif($windefendExists){
try{
$null=Set-MpPreference -DisableRealtimeMonitoring $true -EA Stop
write-host "Windows Defender Realtime-Monitoring has been disabled on $env:computername."
$success=$true
}catch{
write-warning $_
$success=$false
}
}
return $success
}
$results=[hashtable]@{}
$sessionTimeout=New-PSSessionOption -OpenTimeout 120000 # 2 minutes
$sessionIncludePort=New-PSSessionOption -IncludePortInSPN -OpenTimeout 120000
foreach($computername in $computerNames){
$psSession=if($credentials){
try{
New-PSSession -ComputerName $computername -Credential $credentials -ea Stop -SessionOption $sessionTimeout
}catch{
New-PSSession -ComputerName $computername -Credential $credentials -SessionOption $sessionIncludePort
}
}else{
try{
New-PSSession -ComputerName $computername -ea Stop -SessionOption $sessionTimeout
}catch{
New-PSSession -ComputerName $computername -SessionOption $sessionIncludePort
}
}
$result=invoke-command -Session $psSession -ScriptBlock{
param ($uninstallWindefender)
return [scriptblock]::create($uninstallWindefender).invoke()
} -Args ${function:uninstallWindefender}
$results[$computername]=$result
Remove-PSSession $psSession
}
write-output $results|ft -autosize
Categories: