batch files to create and delete text to windows hosts file with task scheduler
-
21-12-2019 - |
Question
The goal is to utilize the task scheduler to block facebook from a designated time to increase productivity and reduce distractions. I deleted facebook for seven months. I don't want to use third party software. Please help me. Also if you have an easier method or better code please show.
Here is what I have.
I have this batch file = blockfacebook.bat executed a particular time which works:
echo 0.0.0.0 www.facebook.com >> c:\windows\system32\drivers\etc\hosts
Although the next batch file = unblockfacebook.bat has the result of completely emptying the hosts file:
type c:\windows\system32\drivers\etc\hosts | findstr /v facebook > c:\windows\system32\drivers\etc\hosts
Could anyone tell me what I am doing wrong with the unblockfacebook.bat
Thank you,
AEGIS
Solution
@echo off
setlocal enableextensions disabledelayedexpansion
set "file=c:\windows\system32\drivers\etc\hosts"
for /f "tokens=* delims=0123456789" %%a in (
'findstr /n /i /v /c:"facebook" "%file%" ^& type nul ^> "%file%"'
) do (
set "line=%%a"
setlocal enabledelayedexpansion
>>"%file%" echo(!line:~1!
endlocal
)
endlocal
This code uses findstr
to filter the input lines and number the output (numbering the lines ensures the empty lines in input file are also readed, processed and written to output), and removes the content of the input file. As for /f
has cached the output of findstr
in memory, and findstr
has ended processing the data, there is no problem to do it.
Then for
starts to process the input (the output of findstr
). It is a list of numbered lines. To remove the numbers, they are used as delimiters in the for
command. As the lines start with delimiters, they are removed until a non delimiter character is found, the colon that separates the numbers from the line content (colon has not been used as delimiter to avoid problems with lines starting with a colon per example some ipv6 address)
Now, with the numbers removed from start all that needs to be done is to remove the first character and append the lines to the input/output file (that was emptied).
OTHER TIPS
type c:\windows\system32\drivers\etc\hosts | findstr /v facebook > c:\users\aegis\desktop\grr.txt
type c:\users\aegis\desktop\grr.txt > c:\windows\system32\drivers\etc\hosts
That's the solution I figured it out when I read this. Although more effective or alternative methods are always appreciated.