Hello,
Thank you for posting the question on Microsoft Windows forum!
The problem you described does not appear to be with the script itself but is caused by the permissions used when executing the script through a GPO. When you run the script locally as an "administrator," it inherits all the necessary permissions to modify protected files (such as the HOSTS file located at C:\Windows\System32\drivers\etc\hosts
). However, when the script is executed via a GPO—whether as a startup script or a logon script—the security context is different, and even when using the system account, it often does not have the same permissions, which results in the file not being modified.
You can ensure that the HOSTS file has the appropriate permissions for modification. You can use a GPO to explicitly configure the ACL (Access Control List) for that file. For example, you can follow this path:
Computer Configuration → Policies → Windows Settings → Security Settings → File System
Under this path, you can add a new entry that points to the HOSTS file, and then grant write permissions either to the required group or directly to the Local System account. This way, the system account will also be able to modify the HOSTS file via the script.
Hope the above steps are helpful!