configure-defender-exclusions.ps1 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # 为 IntelliJ IDEA 与当前项目配置 Microsoft Defender 排除项
  2. # 使用方式:右键此文件,选择“使用 PowerShell 运行”
  3. # 脚本会自动请求管理员权限,并跳过已经存在的排除项。
  4. $ErrorActionPreference = "Stop"
  5. # 检查管理员权限;如果不是管理员,则请求提权后重新运行。
  6. $currentIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
  7. $currentPrincipal = New-Object Security.Principal.WindowsPrincipal($currentIdentity)
  8. $isAdministrator = $currentPrincipal.IsInRole(
  9. [Security.Principal.WindowsBuiltInRole]::Administrator
  10. )
  11. if (-not $isAdministrator) {
  12. Write-Host "正在请求管理员权限..." -ForegroundColor Yellow
  13. $arguments = @(
  14. "-NoProfile"
  15. "-ExecutionPolicy", "Bypass"
  16. "-File", "`"$PSCommandPath`""
  17. )
  18. Start-Process powershell.exe -Verb RunAs -ArgumentList $arguments
  19. exit
  20. }
  21. # 仅排除 JetBrains 缓存、依赖及构建产物。
  22. # 这样可以提升 IDEA、Maven、Vite 的性能,同时保留对项目源码的实时保护。
  23. $pathsToExclude = @(
  24. "C:\Users\CRK\AppData\Local\JetBrains\IntelliJIdea2023.3",
  25. "D:\AAAAA\AAA-sans\client\node_modules",
  26. "D:\AAAAA\AAA-sans\client\dist",
  27. "D:\AAAAA\AAA-sans\server\target",
  28. "D:\AAAAA\AAA-sans\server\data",
  29. "D:\AAAAA\AAA-sans\server\exports"
  30. )
  31. try {
  32. $existingExclusions = @((Get-MpPreference).ExclusionPath)
  33. foreach ($path in $pathsToExclude) {
  34. if ($existingExclusions -contains $path) {
  35. Write-Host "已存在,跳过:$path" -ForegroundColor DarkGray
  36. continue
  37. }
  38. Add-MpPreference -ExclusionPath $path
  39. Write-Host "已添加排除项:$path" -ForegroundColor Green
  40. }
  41. Write-Host ""
  42. Write-Host "Microsoft Defender 排除项配置完成。" -ForegroundColor Cyan
  43. Write-Host "当前相关排除项:" -ForegroundColor Cyan
  44. (Get-MpPreference).ExclusionPath |
  45. Where-Object {
  46. $_ -like "C:\Users\CRK\AppData\Local\JetBrains*" -or
  47. $_ -like "D:\AAAAA\AAA-sans*"
  48. } |
  49. ForEach-Object { Write-Host " $_" }
  50. }
  51. catch {
  52. Write-Host "配置失败:$($_.Exception.Message)" -ForegroundColor Red
  53. Write-Host "请确认 Microsoft Defender 已启用,并且当前账号具有管理员权限。" -ForegroundColor Yellow
  54. exit 1
  55. }
  56. Write-Host ""
  57. Read-Host "按 Enter 键关闭窗口"