01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | $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: