summaryrefslogtreecommitdiffstats
path: root/test/lib/ansible_test/_data/playbooks/windows_hosts_restore.ps1
blob: ac19ffe847bca74de76d4895eb31fe9c832f5523 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<#
.SYNOPSIS
Remove one or more hosts entries from the Windows hosts file.

.PARAMETER Hosts
A list of hosts entries, delimited by '|'.
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory = $true, Position = 0)][String]$Hosts
)

$ProgressPreference = "SilentlyContinue"
$ErrorActionPreference = "Stop"

Write-Verbose -Message "Removing host file entries"

$hosts_entries = $Hosts.Split('|')
$hosts_file = "$env:SystemRoot\System32\drivers\etc\hosts"
$hosts_file_lines = [System.IO.File]::ReadAllLines($hosts_file)
$changed = $false

$new_lines = [System.Collections.ArrayList]@()

foreach ($host_line in $hosts_file_lines) {
    if ($host_line -in $hosts_entries) {
        $changed = $true
    }
    else {
        $new_lines += $host_line
    }
}

if ($changed) {
    Write-Verbose -Message "Host file has extra entries, removing extra entries"
    [System.IO.File]::WriteAllLines($hosts_file, $new_lines)
}