Update/Add/Append Entries in Hosts File using Intune

The hosts file in Windows is a plain text file that maps hostnames (e.g. cloudinfra.net) to IP addresses (e.g. 192.168.1.1). It is one of the first steps your computer uses when resolving domain names to IP addresses before checking with DNS servers.

When you type a website address (e.g., cloudinfra.net) into your browser, the computer first checks the local hosts file to see if there’s an entry for that hostname. If an entry exists, the browser uses the specified IP address. If no entry is found, it moves on to use DNS servers to resolve the domain name.

The file called hosts is located in C:\Windows\System32\drivers\etc folder. Hosts file consists of lines containing IP addresses followed by one or more hostnames. For example:

127.0.0.1 localhost
192.168.1.222 google.com

Windows hosts file location
Windows hosts file location

If you are a local administrator on a Windows device, you can log in to the device, navigate to C:\Windows\System32\drivers\etc, open the hosts file using Notepad, and manually add the IP address and hostname entry. However, if you need to update the hosts file on thousands of devices and also regularly check this file to ensure the entries are still there, manual methods are not practical.

To achieve the goal of updating the hosts file on all Windows devices, you can use a PowerShell script and deploy it through various methods, such as Group Policy, Remote PowerShell, or any MDM solution.

Since all of our devices are enrolled and managed by Intune, today we will use the Intune admin center, specifically Intune device remediations, for this task. Before we proceed, there are a few prerequisites for using Intune device remediations. Let’s take a look.

Delete Entries from Hosts File using Intune.

Related

Prerequisites

  • Device must be Microsoft Entra joined or Entra Hybrid joined.
  • Device must be enrolled and managed by Intune.
  • Supported Windows operating systems are: Enterprise, Professional, or Education edition of Windows 10 or later.
  • Windows 10/11 Enterprise E3 or E5 (included in Microsoft 365 F3, E3, or E5)
  • Windows 10/11 Education A3 or A5 (included in Microsoft 365 A3 or A5)
  • Windows 10/11 Virtual Desktop Access (VDA) per user

Create a Script Package

To create a script package and deploy it on target Windows devices, we will need two scripts.

The first script is a detection script, which checks and confirms whether the specified IP addresses and hostname entries exist in the hosts file. If these entries are not found, the remediation script will execute to add/append the necessary IP addresses and hostname entries to the hosts file.

  • Sign in to the Intune admin center.
  • Go to Devices Scripts and remediatons.
  • Click on + Create under the Remediations tab.

On Basics tab, Provide a Name, Description and Publisher Information of the remediation script package.

Create an Intune Remediation package for updating Hosts file in Windows devices
Create an Intune Remediation package for updating Hosts file in Windows devices

Settings Tab

In the Settings tab, you need to provide the detection and remediation scripts that will execute and update the hosts file on target Windows devices. Below, I have included the content of the scripts. You can also download the scripts from my GitHub page: GitHub – Jatin Makhija.

  1. Create a detection script using the Powershell code below. Save it as UpdateHosts_Detection.ps1.

You will need to update the variable called $HostEntries in the UpdateHosts_Detection.ps1 file to include the IP address and hostname values that you want to add to the hosts file. Please note that existing entries in the hosts file will not be removed; the script will only add or append to the existing entries.

Do not modify anything else in the script aside from the $HostEntries variable, as no other changes are required.

Update $HostEntries variable in the UpdateHosts_Detection.ps1 script

$hostEntries = @(
    @{ ipAddress = "192.168.1.23"; hostname = "cloudinfra.net" },
    @{ ipAddress = "159.233.111.000"; hostname = "techpress.net" },
    @{ ipAddress = "1.2.3.4"; hostname = "testsite.com" }
)

UpdateHosts_Detection.ps1

<#
.SYNOPSIS
    This script checks if specified IP address and hostname pairs exist in the Windows hosts file.
    
.DESCRIPTION
    The script reads a list of IP address and hostname pairs and checks if they exist in the Windows hosts file.
    If any entries are missing, the script logs them in a specified file and exits with a status code 1.
    If all entries are found, it exits with a status code 0.

.PARAMETER $hostEntries
    A list of IP address and hostname pairs to check against the hosts file.
    
.PARAMETER $missingEntriesFilePath
    The file path where missing host entries will be saved, if any are not found in the hosts file.

.NOTES
    Author: Jatin Makhija
    Copyright: cloudinfra.net
    Version: 1.0.0
    
.EXAMPLE
    To run the script and check for missing host entries:
    .\Detection_Hosts.ps1
    
    This will check if the specified entries exist in the hosts file, and output any missing entries.
#>

# List of host entries to check
$hostEntries = @(
    @{ ipAddress = "192.168.1.23"; hostname = "cloudinfra.net" },
    @{ ipAddress = "159.233.111.000"; hostname = "techpress.net" },
    @{ ipAddress = "1.2.3.4"; hostname = "testsite.com" }
)

# Use $env:Windir to dynamically set paths
$windowsDir = $env:Windir

# Dynamically set the hosts file path using Join-Path
$hostsFilePath = Join-Path -Path $windowsDir -ChildPath "System32\drivers\etc\hosts"

# Set the path for missing entries file using Join-Path
$missingEntriesFilePath = Join-Path -Path $windowsDir -ChildPath "Web\MissingEntries.txt"

# Check if the missing entries file exists, and remove it if found
if (Test-Path $missingEntriesFilePath) {
    Remove-Item -Path $missingEntriesFilePath -Force
    Write-Output "Deleted existing missing entries file: $missingEntriesFilePath"
}

# Read the hosts file, excluding comment lines
$hostsFileContent = Get-Content -Path $hostsFilePath | Where-Object {$_ -notmatch "^#"}

# Initialize an array to store missing entries
$missingEntries = @()

# Check each host entry in the list
foreach ($hostEntry in $hostEntries) {
    $entryString = "$($hostEntry.ipAddress) $($hostEntry.hostname)"
    Write-Output "Checking if hosts file contains record: $entryString"

    if ($hostsFileContent -notcontains $entryString) {
        Write-Output "Host $entryString doesn't exist."
        $missingEntries += $entryString
    } else {
        Write-Output "Host $entryString already exists in the hosts file."
    }
}

# Output missing entries to the specified file, if any, and exit with code 1
if ($missingEntries.Count -gt 0) {
    $missingEntries | Out-File -FilePath $missingEntriesFilePath
    Write-Output "Missing entries written to $missingEntriesFilePath"
    Exit 1
} else {
    # All entries exist, exit with code 0
    Write-Output "All specified hosts are present in the hosts file."
    Exit 0
}
  • Create a remediation script using the Powershell code below. Save it as UpdateHosts_Remediation.ps1.

UpdateHosts_Remediation.ps1

<#
.SYNOPSIS
    This script appends missing host entries from the MissingEntries.txt file into the Windows hosts file.

.DESCRIPTION
    The script reads IP address and hostname pairs from the MissingEntries.txt file and adds them to the Windows hosts file. 
    It ensures the entries are appended to the hosts file if they were previously found missing.

.PARAMETER $missingEntriesFilePath
    The path to the file that contains missing host entries to be added to the hosts file.

.PARAMETER $hostsFilePath
    The path to the Windows hosts file where missing entries will be appended.

.NOTES
    Author: Jatin Makhija
    Copyright: cloudinfra.net
    Version: 1.1.0

.EXAMPLE
    To run the script:   
    .\AddMissingEntriesToHosts.ps1 
    This will check the MissingEntries.txt file for missing host entries and append them to the hosts file.    
#>

# Use $env:Windir to dynamically set paths
$windowsDir = $env:Windir

# Define the path to the missing entries file
$missingEntriesFilePath = Join-Path -Path $windowsDir -ChildPath "Web\MissingEntries.txt"

# Check if the missing entries file exists
if (Test-Path $missingEntriesFilePath) {
    # Read the missing entries from the file
    $missingEntries = Get-Content -Path $missingEntriesFilePath

    # Define the path to the hosts file using Join-Path
    $hostsFilePath = Join-Path -Path $windowsDir -ChildPath "System32\drivers\etc\hosts"

    # Append each missing entry to the hosts file
    foreach ($entry in $missingEntries) {
        Add-Content -Path $hostsFilePath -Value $entry
        Write-Output "Appended $entry to the hosts file."
    }
    
    Write-Output "All missing entries have been added to the hosts file."
    Exit 0
} else {
    # Missing entries file not found
    Write-Output "No missing entries file found at $missingEntriesFilePath."
    Exit 1
}
  • Detection script file – Browse to the Detection script UpdateHosts_Detection.ps1
  • Remediation script file – Browse to Remediation script file UpdateHosts_Remediation.ps1
  • Run this script using the logged-on credentials – No
  • Enforce script signature check – No
  • Run script in 64-bit Powershell – Yes
Upload Detection and Remediation scripts for adding entries to the hosts file
Upload Detection and Remediation scripts for adding entries to the hosts file

Assignments tab

To add an Entra security group containing users or devices, click on Select groups to include.

Next, configure how often you want the Intune remediation package to execute on the target devices by using the Schedule setting. Click on the Daily hyperlink, and then select the Frequency option: either Once, Hourly, or Daily. For this setup, we’ll choose Daily and set it to repeat every 1 day.

Assign the script package to Intune managed windows devices
Assign the script package to Intune managed windows devices

Review + Create

Review the deployment and click on Create to start the deployment process.

If you are wondering where the scripts are downloaded on the Client machine before execution, the location is: C:\Program Files (x86)\Microsoft Intune Management Extension\Policies\Scripts. For more information refer to the link: Where Does Intune Cache PowerShell Scripts on End User Devices? – Scroll down on the page to find more info.

Note

Sync Intune Policies

The device check-in process might not begin immediately. If you’re testing this policy on a test device, you can manually kickstart Intune sync from the device itself or remotely through the Intune admin center.

Alternatively, you can use PowerShell to force the Intune sync on Windows devices. Restarting the device is another way to trigger the Intune device check-in process.

End User Experience

After the deployment is completed successfully, check the hosts file on target windows devices by following below steps:

  • Sign in to one of the target windows device.
  • Go to C:\Windows\System32\drivers\etc location.
  • Open hosts file using Notepad.
  • Verify if the entries are added as per the deployment
Verification of the script package confirming the records are added into the hosts file
Verification of the script package confirming the records are added into the hosts file

Monitor the script package

The status of the Remediation script package might not be available immediately on the Intune portal. If you do not see any data populated yet then please wait and the data will appear once the Intune sync is completed.

To Monitor the progress of a script package deployed via Intune, follow the below steps:

  • Sign in to the Intune admin center.
  • Go to Devices > Scripts and Remediations.
  • Click on the Remediation script package you want to monitor- for example, Update Hosts file on Windows Devices.
Monitor Intune remediation script package to check the status of the deployment
Monitor Intune remediation script package to check the status of the deployment
This screenshot confirmed that there was 1 computer with Issues and 1 Issue Fixed
This screenshot confirmed that there was 1 computer with Issues and 1 Issue Fixed

Where to find Intune Remediation Logs?

To access Intune device remediation logs and locate the log file related to this script package deployment, follow these steps:

  • Browse to C:\ProgramData\Microsoft\IntuneManagementExtension\Logs.
  • Look for this directory’s most recent version of the IntuneManagementExtension.log file.
  • Search using the Script Package GUID to jump to the logs related to your deployment.
  • For a more user-friendly log viewing experience, consider using a tool like CMTrace.
Intune device remediation log file and verification of the script package execution
Intune device remediation log file and verification of the script package execution
Detailed Information about Intune Management Extension (IME) Log Files
Detailed Information about AppWorkload.log file

Read Next

Leave a Comment