(imported comment written by SystemAdmin)
I came across this one while searching for something similar. Figured I’d post what we did, which improves on this a little.
I’d also suggest using “%0d%0a” (CRLF) rather than “%0a%0d” (LFCR). Simple editors like Notepad won’t display the file properly unless it’s CRLF.
I don’t think I’d agree with blindly deleting lines 20 and 21 in the above case without the relevence confirming those lines first. Here’s the way we did it, also backing up the hosts file first. I always keep the last hosts file as hosts-old, and if a hosts-old exists I’ll rename that to today’s date.
I’m also making sure that the name in the hosts file isn’t case sensitive, and I don’t care about lines commented out (properly or white space to the left)
Assuming you wanted to remove “143.182.113.108” AND “atdscppweb01”…
Relevance:
exists file “hosts” whose (exists lines whose (it as left trimmed string does not start with “#” and it contains “143.182.113.108” ) of it OR exists lines whose (it as left trimmed string does not start with “#” and it as lowercase contains “atdscppweb01” ) of it) of folder “drivers\etc” of system folder
Action:
// Remove entries from the HOSTS file. If HOSTS-OLD exists, back that up to HOSTS-mmDDDYYYY-hhmm
// Previous HOSTS will remain as HOSTS-OLD
if {exists file “hosts-old” of folder “drivers\etc” of system folder}
move “{pathname of system folder}\drivers\etc\hosts-old” “{pathname of system folder}\drivers\etc\hosts-{(first 2 of it & substring between " " of it & last 4 of it) of (following text of position 5 of preceding text of position 16 of (now as string)) & “-” & (first 2 of it & last 2 of it) of (following text of position 17 of preceding text of last “:” of (now as string))}”
endif
delete __appendfile
appendfile {concatenation “%0d%0a” of lines whose (it as left trimmed string starts with “#” OR (it as lowercase does not contain “atdscppweb01” and it does not contain “143.182.113.108” )) of file “hosts” of folder “drivers\etc” of system folder}
move “{pathname of system folder}\drivers\etc\hosts” “{pathname of system folder}\drivers\etc\hosts-old”
move __appendfile “{pathname of system folder}\drivers\etc\hosts”