How to Add HOST file Entry using PowerShell?

Here is the nifty PowerShell script to add HOST file entry using PowerShell:

$HostFile = 'C:\Windows\System32\drivers\etc\hosts'

# Create a backup copy of the Hosts file
$dateFormat = (Get-Date).ToString('dd-MM-yyyy hh-mm-ss')
$FileCopy = $HostFile + '.' + $dateFormat  + '.copy'
Copy-Item $HostFile -Destination $FileCopy

#Hosts to Add
$Hosts = @("intranet.Crescent.com", "Intranet", "mysite.crescent.com")

# Get the contents of the Hosts file
$File = Get-Content $HostFile

# write the Entries to hosts file, if it doesn't exist.
foreach ($HostFileEntry in $Hosts) 
{
    Write-Host "Checking existing HOST file entries for $HostFileEntry..."
    
    #Set a Flag
    $EntryExists = $false
    
    if ($File -contains "127.0.0.1 `t $HostFileEntry") 
    {
        Write-Host "Host File Entry for $HostFileEntry is already exists."
        $EntryExists = $true
    }
    #Add Entry to Host File
    if (!$EntryExists) 
    {
        Write-host "Adding Host File Entry for $HostFileEntry"
        Add-content -path $HostFile -value "127.0.0.1 `t $HostFileEntry"
    }
}

SharePoint HOST File PowerShell

Add entry to HOST file using PowerShell

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

One thought on “How to Add HOST file Entry using PowerShell?

  • This is a nifty script for adding host entries. Would you know if there is a similar one to remove the entries for cleanup?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *