Delete Entries from Hosts File using Intune

In my previous blog post, I discussed about the Hosts file in Windows – its purpose, structure, and how to Add/Append entries in the hosts file using Intune. You can refer to that post for more detailed information.

You may need to add records to the Hosts file for various reasons, such as testing a web application, troubleshooting a DNS issue, or other tasks. Whatever the reason, once the testing is complete, you may want to remove those temporary entries from the Hosts file.

In this post, we will focus on removing or deleting given entries from the Hosts file without affecting the existing records.There are several methods for removing entries from the Hosts file, such as using PowerShell scripts or Active Directory Group Policy. However, today we will be using Intune device remediations for this purpose.

Before we proceed, there are a few prerequisites to consider when using Intune device remediations. Let’s review them.

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 found, the remediation script will execute to remove/delete the necessary IP addresses and hostname entries to the hosts file without affecting the existing records.

  • 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 NameDescription and Publisher Information of the remediation script package.

Create a script package to delete given entries from hosts file using Intune admin center
Create a script package

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.

  • Create a detection script using the Powershell code below. Save it as Detection_Host_Entries.ps1

You will need to update the variable called $HostEntries in the Detection_Host_Entries.ps1 file to include the IP address and hostname values that you want to delete/remove to the hosts file. Please note that existing entries in the hosts file will not be removed; the script will only delete the entries you specify in the detection powershell script. Do not modify anything else in the script aside from the $HostEntries variable, as no other changes are required.

Update $HostEntries variable in the Detection_Host_Entries.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" }
)

Detection_Host_Entries.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 found, the script logs them in a specified file and exits with a status code 1.
    If no 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 $foundEntriesFilePath
    The file path where found host entries will be saved, if any are found in the hosts file.

.NOTES
    Author: Jatin Makhija
    Copyright: Cloudinfra.net
    Version: 1.0
    
.EXAMPLE
    To run the script and check for existing host entries:
    .\Detection_Host_Entries.ps1
    
    This will check if the specified entries exist in the hosts file, and output any found entries.
#>

$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 Enviornment variable
$windowsDir = $env:Windir

# Build paths dynamically using Join-Path
$hostsFilePath = Join-Path -Path $windowsDir -ChildPath "System32\drivers\etc\hosts"
$foundEntriesFilePath = Join-Path -Path $windowsDir -ChildPath "Web\FoundEntries.txt"

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

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

# Initialize an array to store found entries
$foundEntries = @()

function Normalize-Entry {
    param (
        [string]$entry
    )
    return ($entry -split '\s+' | ForEach-Object { $_.Trim() }) -join ' '
}

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

    # Normalize each line from the hosts file before comparison
    foreach ($line in $hostsFileContent) {
        $normalizedLine = Normalize-Entry $line

        if ($normalizedLine -eq $entryString) {
            Write-Output "Host $entryString exists."
            $foundEntries += $entryString
            break
        }
    }
}

# Output found entries to the specified file, if any, and exit with code 1
if ($foundEntries.Count -gt 0) {
    $foundEntries | Out-File -FilePath $foundEntriesFilePath
    Write-Output "Found entries written to $foundEntriesFilePath"
    Exit 1
} else {
    # No entries exist, exit with code 0
    Write-Output "None of the specified hosts are present in the hosts file."
    Exit 0
}
  • Create a remediation script using the Powershell code below. Save it as Remediation_Host_Entries.ps1.

Remediation_Host_Entries.ps1

<#
.SYNOPSIS
    This script removes specific host entries (IP and hostname pairs) found in the FoundEntries.txt file from the Windows hosts file.

.DESCRIPTION
    The script reads IP address and hostname pairs from the FoundEntries.txt file and removes them from the Windows hosts file.
    It ensures that only the specified entries are removed, and all other entries remain unchanged.

.PARAMETER $foundEntriesFilePath
    The path to the file that contains host entries to be removed from the hosts file.

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

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

.EXAMPLE
    To run the script:   
    .\Remediation_Host_Entries.ps1
    This will check the FoundEntries.txt file for host entries and remove them from the hosts file.    
#>

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

# Define the path to the FoundEntries.txt file using Join-Path
$foundEntriesFilePath = Join-Path -Path $windowsDir -ChildPath "Web\FoundEntries.txt"

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

function Normalize-Entry {
    param (
        [string]$entry
    )
    return ($entry -replace "\s+", " ").Trim()
}

# Check if the FoundEntries.txt file exists
if (Test-Path $foundEntriesFilePath) {
    $foundEntries = Get-Content -Path $foundEntriesFilePath | ForEach-Object { Normalize-Entry $_ }

    # Read the current contents of the hosts file
    $hostsFileContent = Get-Content -Path $hostsFilePath

    # Initialize an array to store the updated hosts file content
    $updatedHostsFileContent = @()

    foreach ($line in $hostsFileContent) {
        $normalizedLine = Normalize-Entry $line

        # Check if the line is NOT in the found entries list
        if ($foundEntries -notcontains $normalizedLine) {
            # If the line is not found in the list, add it to the updated content
            $updatedHostsFileContent += $line
        } else {
            Write-Output "Removing entry: $normalizedLine"
        }
    }

    # Write the updated content back to the hosts file
    Set-Content -Path $hostsFilePath -Value $updatedHostsFileContent
    Write-Output "Updated hosts file. Entries from FoundEntries.txt have been removed."
    Exit 0
} else {
    # FoundEntries.txt file not found
    Write-Output "No FoundEntries file found at $foundEntriesFilePath."
    Exit 1
}
  • Detection script file – Browse to the Detection script Detection_Host_Entries.ps1
  • Remediation script file – Browse to Remediation script file Remediation_Host_Entries.ps1
  • Run this scrip using the logged-on credentials – No
  • Enforce script signature check – No
  • Run script in 64-bit Powershell – Yes
Upload Detection and Remediation scripts which will delete entries from hosts file
Upload Detection and Remediation scripts which will delete entries from 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 OnceHourly, or Daily. For this setup, we’ll choose Daily and set it to repeat every 1 day.

Assign the script package to Windows devices
Assign the script package to 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?

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 deleted as per the intune deployment.
Given Entries in the script package have been removed from hosts file on a Windows Device
Given Entries in the script package have been removed from hosts file on a Windows Device

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, Delete Entries from Hosts file on Windows Devices.

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 Management Extension logs for Detection and Remediation Script
Intune Management Extension logs for Detection and Remediation Script

Read Next

Leave a Comment