DEV Community

cuongld2
cuongld2

Posted on

Modify hosts file using powershell

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



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



Enter fullscreen mode Exit fullscreen mode

Without # that will be activatted

is for comment the line

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

  1. Scenario

For example we need to modify the hosts file as below



#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



Enter fullscreen mode Exit fullscreen mode

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

3.What we need to work:

  • Open new powershell window as administration


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'



Enter fullscreen mode Exit fullscreen mode
  • Replace the text:

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



(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



Enter fullscreen mode Exit fullscreen mode
  • 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



(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


Enter fullscreen mode Exit fullscreen mode

'#+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




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
}



Enter fullscreen mode Exit fullscreen mode
  • Provide value to $action param from command line

Define param for action in the script:



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

}



Enter fullscreen mode Exit fullscreen mode

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))

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



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"



Enter fullscreen mode Exit fullscreen mode

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 :

This will help me to contributing more valued contents.

Top comments (0)