How to Block Specific URLs Using a PowerShell Script Run from a Scheduled Task

I’m working in the company where most of the users are remote users who work on the computers joined to domain. During most of the workday users do not connect to the corporate network, nay, their computers can retinas without connection to the domain whole days. Also, it is quite common for users’ machines not to be powered off at the end of the workday but to be hibernated. All these in sum causes the domain policy to be propagated to users’ machines too slow, and logon script can executes once a week (if God helps). As well, when they sign in their machines, they are usually not connected to the domain. It may be added that, users are quite mobile and can move over the globe quite often.

With all this in hand, I had a task to block some URLs on the machines depending on what country the users are in at the moment. The easiest way I see is just adding entries to the file %SystemRoot%System32driversetchosts like this one:

127.0.0.1 site_to_be_blocked

when the user entries the country where the block must be on (and then removing the entry when the user leaves the country).

I thought that a good solution would be to use a powershell script that would be periodically run from a task in the Windows Task Scheduler, and the task would be pushed on the user’s computers with GPO.

The script is already done and signed with a domain certificate. The latter gave me an unfounded and unjustifiable confidence that there should be no problems when executing the script from the task. By design, the script should be in \my_domainSYSVOLbla-bla-bla and called on users’ machines by the task pushed with GPO. When executed, the script creates a copy of itself on the user’s machine and a new task that periodically runs the local script, and thus the execution of the script becomes independent of whether the user is connected to the corporate network or not. The script works perfect in PowerShell ISE.

The task is run on behalf of SYSTEM and ‘Run with highest privileges’ checkbox is also ticked. The task calls powershell.exe with arguments -ExecutionPolicy Bypass -File "pathscript.ps1"
The plan seemed perfect 🙂 until its realization.
I face an issue I have been struggling for hours with (for days to be honest). The problem that the script doesn’t work in the task. And I have no idea how to fix it.

I would appreciate any your advice. Perhaps you could even give a new direction how the task can be done if you think there is no prospect in using PS scripts.

If you are wondering how new entries are appended to the hosts file, here is what the script does:

$hostsPath = "$env:SystemRootSystem32driversetchosts"

Add-Content -Path $hostsPath -Value $newEntry -Force -NoNewline

where $newEntry contains a string that makes the unwanted URL referencing address 127.0.0.1