Advertisement
Guest User

Auto-Update Hosts file

a guest
Mar 29th, 2020
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. $global:hosts = "C:\Windows\system32\drivers\etc\hosts"
  2. $global:url = "https://someonewhocares.org/hosts/hosts"
  3. $global:temp = "C:\temp\hosts"
  4. $global:logFile = "C:\_Scripts\Update_Hosts_File.log"
  5.  
  6. Enum LogLevel {
  7. Info = 0
  8. Warning = 1
  9. Error = 2
  10. }
  11.  
  12. function Write-Log ([string]$message, [LogLevel]$logLevel) {
  13. if ($null -eq $logLevel) {
  14. $logLevel = [LogLevel]::Info
  15. }
  16.  
  17. if ($logLevel -eq [LogLevel]::Info) {
  18. Add-Content -Path $logFile -Value "$(Get-Date): $message"
  19. Write-Host $message
  20. }
  21. elseif ($logLevel -eq [LogLevel]::Warning) {
  22. Add-Content -Path $logFile -Value "$(Get-Date): WARNING: $message"
  23. Write-Host $message -ForegroundColor Yellow
  24. }
  25. elseif ($logLevel -eq [LogLevel]::Error) {
  26. Add-Content -Path $logFile -Value "$(Get-Date): ERROR: $message"
  27. Write-Host $message -ForegroundColor Red
  28. }
  29. }
  30.  
  31. Write-Log "Script started."
  32. try {
  33. Write-Log "Downloading hosts file from URL $url..."
  34. Invoke-WebRequest -Uri $url -OutFile $temp
  35. $newHash = (Get-FileHash -Path $temp -Algorithm SHA256).Hash
  36. $oldHash = (Get-FileHash -Path $hosts -Algorithm SHA256).Hash
  37.  
  38. if ($newHash -ne $oldHash) {
  39. Write-Log "Copying new file..."
  40. Move-Item -Path $temp -Destination $(Split-Path $hosts) -Force
  41. Write-Log "Done."
  42. }
  43. else {
  44. Write-Log "File is up to date."
  45. }
  46. }
  47. catch {
  48. Write-Log "Script failed: $($_.Exception.Message)" Error
  49. exit 1
  50. }
  51. Write-Log "Script finished."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement