Modify hosts file using powershell
Tags: hosts, windows, powershell, administration
Published: 2020-02-13 09:42:36

---
title: Modify hosts file using powershell
published: true
description: 
tags: #hosts #windows #powershell #administration
---

Recently, I need to modify the hosts during automation testing for windows app.
Just find out powershell is a great shell for doing stuffs in windows 10 ( powershell is pre-installed since windows 8)

1. What is hosts file:
Hosts file is a file that maps hostnames to IP addresses.
For example

```javascript

# localhost name resolution is handled within DNS itself.
#	127.0.0.1       localhost
#	::1             localhost

```
Without # that will be activatted
# is for comment the line

To modify the hosts file, you will need to open the file as administrator

2. Scenario

For example we need to modify the hosts file as below

```javascript
#10.3.4.53 browser.beebee.com
#10.3.4.53 update.beebee.vn
#10.3.4.53 metrics.beebee.vn
#10.3.4.53 service.beebee.vn
#10.3.4.53 beebee.vn
#10.3.4.53 beebee.com.vn
#10.3.4.53 beebee.com
#10.3.4.53 beebee.com
#10.3.4.53 beebee.vn
#10.3.4.53 beebee.beebee.com

#10.3.4.53 dev-update-browser.itim.vn

```
We need to activate and deactivate the dev environment for beebee server

3.What we need to work:
- Open new powershell window as administration

```javascript
param([switch]$Elevated)


function Test-Admin {
  $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
  $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

if ((Test-Admin) -eq $false)  {
    if ($elevated) 
    {
        # tried to elevate, did not work, aborting
    } 
    else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated ' -f ($myinvocation.MyCommand.Definition))
}

exit

}

'running with full privileges'

```

- Replace the text:

Use Get-Content and Set-Content command to replace the text

```javascript
(Get-Content C:\Windows\System32\drivers\etc\hosts -Raw) -replace '10.3.4.53','#10.3.4.53' | Set-Content -Path C:\Windows\System32\drivers\etc\hosts

```

- Replace the text with regex:

There are times, that we have many '#' character before the '10.3.4.53'. We would want to replace all the # with the '10.3.4.53' to '10.3.4.53'

So in this case, we need to do that with regex which also supported in powershell

```javascript
(Get-Content C:\Windows\System32\drivers\etc\hosts -Raw) -replace '#+10.3.4.53','10.3.4.53' | Set-Content -Path C:\Windows\System32\drivers\etc\hosts
```
'#+10.3.4.53' --> '#+' means one or more '#' characters

- Provide conditions to run as if activate or deactivate the hosts file:

Using if and elseif in powershell

```javascript

if ($action -like 'activate')  {
(Get-Content C:\Windows\System32\drivers\etc\hosts -Raw) -replace '#+10.3.4.53','10.3.4.53' | Set-Content -Path C:\Windows\System32\drivers\etc\hosts
Sleep 2
echo $action
}elseif($action -like 'deactivate'){

(Get-Content C:\Windows\System32\drivers\etc\hosts -Raw) -replace '10.3.4.53','#10.3.4.53' | Set-Content -Path C:\Windows\System32\drivers\etc\hosts
Sleep 2
echo $action
}

```

- Provide value to $action param from command line

Define param for action in the script:


```javascript
param([Parameter(Mandatory = $true,ValueFromPipeline = $true)]
	[string]	      
	$action, [switch]$Elevated)


function Test-Admin {
  $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
  $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

if ((Test-Admin) -eq $false)  {
    if ($elevated) 
    {
        # tried to elevate, did not work, aborting
    } 
    else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated -action "{1}"' -f ($myinvocation.MyCommand.Definition,$action))
}

exit

}

```
use that param '-action' when open new powershell as admin
--> Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated -action "{1}"' -f ($myinvocation.MyCommand.Definition,$action))

4. How to run:
Full script will be like:

```javascript

param([Parameter(Mandatory = $true,ValueFromPipeline = $true)]
	[string]	      
	$action, [switch]$Elevated)


function Test-Admin {
  $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
  $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

if ((Test-Admin) -eq $false)  {
    if ($elevated) 
    {
        # tried to elevate, did not work, aborting
    } 
    else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated -action "{1}"' -f ($myinvocation.MyCommand.Definition,$action))
}

exit

}

'running with full privileges'


if ($action -like 'activate')  {
(Get-Content C:\Windows\System32\drivers\etc\hosts -Raw) -replace '#+10.3.4.53','10.3.4.53' | Set-Content -Path C:\Windows\System32\drivers\etc\hosts
Sleep 2
echo $action
}elseif($action -like 'deactivate'){

(Get-Content C:\Windows\System32\drivers\etc\hosts -Raw) -replace '10.3.4.53','#10.3.4.53' | Set-Content -Path C:\Windows\System32\drivers\etc\hosts
Sleep 2
echo $action
}

Sleep 2

Stop-Process -Name "powershell"

```
Save the file as 'script.ps1' file:
Run from powershell as : .\script.ps1 -action 'activate'   --> to activate
Run as .\script.ps1 -action 'activate'  --> to deactivate

That's it. Hope this helps.

Notes: If you feel this blog help you and want to show the appreciation, feel free to drop by :

[<img src="https://thepracticaldev.s3.amazonaws.com/i/cno42wb8aik6o9ek1f89.png">](https://www.buymeacoffee.com/dOaeSPv
)

This will help me to contributing more valued contents.