Category filter
Script to block websites on Windows
Website blacklisting is a defense mechanism that prevents users from accessing harmful and unwanted web URLs. The browser prompts a blocked access notification when the users access the blacklisted websites. Depending on the enterprise requirements, those websites that are unnecessary for the users can be blacklisted. While there are various ways of filtering web content, executing custom scripts is one of the easiest methods of performing it remotely.
Block websites
The host file inside the system’s C drive must be edited to block websites. Execute the following script to modify the host file and specify the websites to be blocked:
1 2 3 4 5 6 7 8 9 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 |
$blockUrlList = @("www.facebook.com", "www.google.com", "www.youtube.com") $defaultHostsFile = @" "@ try { $originalhostsFile= Get-Content C:\Windows\System32\drivers\etc\hosts -ErrorAction Ignore $hostFileExists = $true if(-not($originalhostsFile)) { $hostFileExists = $false $originalhostsFile = $defaultHostsFile } $updatedHostsFile = $originalhostsFile ForEach($url in $blockUrlList) { if($hostFileExists) { $updatedHostsFile = $updatedHostsFile+"127.0.0.1 $url" } else { $updatedHostsFile = $updatedHostsFile+"`n127.0.0.1 $url" } } $updatedHostsFile | Out-File -FilePath C:\Windows\System32\drivers\etc\hosts -Encoding utf8 -Force Write-Host "updated Hosts file->" $updatedHostsFile } catch { Write-Host $_.Exception.Message } |
Enter the websites to be blocked as string inputs and separate them using commas. For instance, in the script given above, “www.facebook.com”, “www.google.com” and “www.youtube.com” are the URLs to be blocked.
Unblock websites
Execute the following script to unblock the previously blocked websites and restore the host file to its default state:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$defaultHostsFile = @" "@ try { $defaultHostsFile | Out-File -FilePath C:\Windows\System32\drivers\etc\hosts -Force -Encoding utf8 Write-Host "Hosts file updated to default->" $defaultHostsFile } catch { Write-Host $_.Exception.Message } |