Set Host(s) File via Intune

Sometimes you need a quick and dirty fix. That quick and dirty fix might be to set the host(s) file via Intune on a Windows 10/11 machine.

I needed that fix. So, I used a remediation to do so. It is quite an easy solution. It uses a detection and a remediation script.

Save these 2 scripts as .ps1 files, we need them later.

This is the detection script:

Start-Transcript -Path C:\ProgramData\Microsoft\IntuneManagementExtension\Logs\Edithostfile_detect.log -Append

$Records = @(
    "10.10.50.134 test.local"
    "10.10.50.135 test.tech"
)

$HostFileContent = Get-Content -Path C:\Windows\System32\drivers\etc\hosts | Where-Object {$_ -notmatch "^#"}

foreach ($Record in $Records) {

    Write-Output "Checking if Hostfile contains record: $Record"

    If ($HostFileContent -notcontains $Record){

        Write-Output "Host $Record doesn't exist, exiting script with code 1"
        Exit 1
        
    }
    else {
        Write-Output "Host $Record already exists in Hostfile"
    }
}

Stop-Transcript

This is the remediation script:

Start-Transcript -Path C:\ProgramData\Microsoft\IntuneManagementExtension\Logs\Edithostfile_remediate.log -Append

$Records = @(
    "10.10.50.134 test.local"
    "10.10.50.135 test.tech"
)

Set-Content -Path "C:\Windows\System32\drivers\etc\hosts" -Value $Records

Stop-Transcript

If you want more hosts in the file. Just add them to the $Records array.

After that, we create the remediation in Microsoft Intune. Go to the Intune portal.

Next, go to Devices and Script and remediations:

Create a new script package:

Set a name and click next:

Add the files we saved earlier in the Detection script file and the Remediation script file.

Set the script to run in 64-bit PowerShell:

(Set the scope tags if you like)

Assign it to a group and for testing purposes I set it to run each hour.

Click Review & Create to save the script package.

Testing

The script logs to the C:\ProgramData\Microsoft\IntuneManagementExtension\Logs\ directory:

The detect log shows that at first the records are not found in the hosts file:

Then the remediation script runs and after that, the detection script runs again:

That’s how you set a host(s) file via Intune.

It also allows you to update it dynamically since you can update the $Records array in the PowerShell script.

Leave a Comment