forked from StevenBlack/hosts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdateHostsWindows.ps1
More file actions
264 lines (258 loc) · 10.4 KB
/
updateHostsWindows.ps1
File metadata and controls
264 lines (258 loc) · 10.4 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
<#
.SYNOPSIS
Install/update hosts files found at https://github.com/StevenBlack/hosts/.
.DESCRIPTION
Install/update consolidated hosts files found at
https://github.com/StevenBlack/hosts/.
.PARAMETER Alternate
Update hosts with one of the alternate hosts file found in Steven's alternates
directory.
.PARAMETER OutFile
Download the file only, do not update. Defaults to the current path.
.PARAMETER NoBackup
Do not create a backup file.
.PARAMETER Force
Force continue the script on errors.
.PARAMETER Restore
Restore the hosts file with the current skeleton backup if one exists and
exits.
.EXAMPLE
PS> .\updateHostsWindows.ps1
.EXAMPLE
PS> .\updateHostsWindows.ps1 -OutFile '.\hosts'
--------------------------------------------------------------------------------
This Powershell script updates the Windows hosts file from one of the various consolidated hosts files found at at: https://github.com/StevenBlack/hosts -------------------------------------------------------------------------------- If updating the hosts file fails due to the hosts file being in use then it's best to just keep trying. It's not always in use though it is hard to figure
out when it's free so it's recommended to use while loop on $LASTEXITCODE to
keep trying. E.G.: while ($LASTEXITCODE -gt 0) { .\updateHostsWindows.ps1 }.
--------------------------------------------------------------------------------
Use: Get-Help .\updateHostsWindows.ps1 -Detailed (or -Full) for more
information.
--------------------------------------------------------------------------------
Checking if we are in a shell with administrative privileges.
Attempting to get data from
https://raw.githubusercontent.com/StevenBlack/hosts/refs/heads/master/hosts.
Attempting to create output file .\hosts.
Successfully created file: .\hosts.
#>
<#
╔════════════════════════════════════════════════════════════════════════╗
║ This Powershell script updates the Windows hosts file from one of the ║
║ various consolidated hosts files found at at: ║
║ https://github.com/StevenBlack/hosts ║
║ This script is written for backwards compatibility for Powershell 5.1+ ║
║ as PowerCore is not installed by default. ║
║ ║
║ Original script written by: ║
║ Ian Pride (Lateralus138) ║
║ faithnomoread@yahoo.com ║
╚════════════════════════════════════════════════════════════════════════╝
#>
<#
╔═══════════════════╗
║ Parse parameters. ║
╚═══════════════════╝
#>
Param(
[String]$Alternate,
[String]$OutFile,
[Switch]$NoBackup,
[Switch]$Force,
[Switch]$Restore
)
<#
╔═══════════════════╗
║ Global variables. ║
╚═══════════════════╝
#>
$seperator = '-' * 80
$baseHostsUrl = 'https://raw.githubusercontent.com/StevenBlack/hosts/refs/heads/master/'
$WriteStatus = {
Param(
[ValidateScript({ $_.Length -gt 0 })][String]$Message,
[Switch]$IsError
)
switch ($IsError){
$true { $color = 'Red' }
default { $color = 'Green' }
}
$lastColor = $host.ui.RawUI.ForegroundColor
$host.ui.RawUI.ForegroundColor = $color
$Message
$host.ui.RawUI.ForegroundColor = $lastColor
}
<#
╔════════════════════╗
║ About this script. ║
╚════════════════════╝
#>
@"
$seperator
This Powershell script updates the Windows hosts file from one of the various
consolidated hosts files found at at: https://github.com/StevenBlack/hosts
$seperator
If updating the hosts file fails due to the hosts file being in use then it's
best to just keep trying. It's not always in use though it is hard to figure
out when it's free so it's recommended to use while loop on `$LASTEXITCODE to
keep trying. E.G.: while (`$LASTEXITCODE -gt 0) { .\updateHostsWindows.ps1 }.
$seperator
Use: Get-Help .\updateHostsWindows.ps1 -Detailed (or -Full) for more
information.
$seperator
"@
<#
╔═════════════════════════════════╗
║ Check administrative privileges ║
╚═════════════════════════════════╝
#>
' Checking if we are in a shell with administrative privileges.'
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator")) {
$argString = ''
$PSBoundParameters.GetEnumerator() | Foreach-Object {
$argString += ' -' + $_.Key + ' ' + $_.Value
}
' Attempting to restart this script as administrator.'
try {
Start-Process powershell `
-ArgumentList "-NoLogo -NoExit -NoProfile -Command `"Set-Location $PWD`; $PSCommandPath $argString`"" `
-Verb RunAs `
-ErrorAction SilentlyContinue
} catch {
&$WriteStatus $(" " + $_.Exception.Message + "`n") -IsError
}
exit 1
}
if ($Alternate -eq 'True') { $Alternate = '' }
if ($OutFile -eq 'True') { $OutFile = '' }
$hostsFile = $Env:SystemRoot + '\System32\drivers\etc\hosts'
$hostsSkeleton = $hostsFile + '.skel'
<#
╔══════════════════════╗
║ Restore last backup. ║
╚══════════════════════╝
#>
if ($Restore){
Write-Host " Attempting to restore $hostsSkeleton"
if (-not (Test-Path -Path $hostsSkeleton -PathType Leaf )) {
&$WriteStatus $(' ' + $hostsSkeleton + " not found.`n") -IsError
exit 2
}
try {
Copy-Item -Path $hostsSkeleton -Destination $hostsFile -ErrorAction Stop
$successMessage =
@"
Successfully restored $hostsSkeleton to $hostsFile.
"@
&$WriteStatus $successMessage
} catch {
&$WriteStatus $(
" Could not restore the hosts file.`n " +
$_.InvocationInfo.MyCommand.Name + ': ' + $_.Exception.Message + "`n If the file was in use please try again. It will eventually be free.`n"
) -IsError
exit 3
}
exit 0
}
<#
╔════════════════════════════╗
║ Backup current hosts file. ║
╚════════════════════════════╝
#>
if (-not ($OutFile)){
switch ($NoBackup){
$true { " No backup will be created." }
default {
" Attempting to create a back up of $hostsFile."
try {
Copy-Item -Path $hostsFile -Destination $hostsSkeleton -ErrorAction Stop
$successMessage =
@"
Successfully created a backup of the current hosts file at
$hostsSkeleton.
"@
&$WriteStatus $successMessage
} catch {
&$WriteStatus $(
" Could not create a backup of the hosts file.`n " +
$_.InvocationInfo.MyCommand.Name + ': ' + $_.Exception.Message
) -IsError
if (-not ($Force)) {
&$WriteStatus " This script will now exit (use the -Force switch to force continue on error).`n" -IsError
exit 4
}
}
}
}
}
<#
╔══════════════════════════╗
║ Select which hosts file. ║
╚══════════════════════════╝
#>
switch ($Alternate.Length -gt 0) {
$true { $hostsUrl = $baseHostsUrl + 'alternates/' + $Alternate + '/hosts' }
default { $hostsUrl = $baseHostsUrl + 'hosts' }
}
<#
╔═════════════════════════════╗
║ Get remote hosts file data. ║
╚═════════════════════════════╝
#>
try {
" Attempting to get data from`n $hostsUrl."
$response = Invoke-WebRequest -Uri $hostsUrl
} catch {
&$WriteStatus $(' ' + $_.Exception.Message + "`n") -IsError
exit 5
}
if (-not($response.StatusDescription -eq 'OK')) {
&$WriteStatus $(
" Could not retrieve a valid reponse from`n $hostsUrl. [" +
$response.StatusCode + '] ' + $response.StatusDescription + "`n"
) -IsError
exit 6
}
<#
╔══════════════════════════════════╗
║ Install, update, or create file. ║
╚══════════════════════════════════╝
#>
if ($OutFile.Length -gt 0){
" Attempting to create output file $OutFile."
try {
$response.Content | Out-File -FilePath $OutFile -Encoding utf8
} catch {
&$WriteStatus $(
" Could not create file: $OutFile.`n " + $_.Exception.Message + "`n"
) -IsError
exit 7
}
&$WriteStatus " Successfully created file: $OutFile.`n"
exit 0
}
" Attempting to update $hostsFile."
try {
$response.Content | Out-File -FilePath $hostsFile -Encoding utf8
} catch {
&$WriteStatus $(
" Could not update: $hostsFile.`n " + $_.Exception.Message + "`n"
) -IsError
exit 8
}
&$WriteStatus " Successfully updated: $hostsFile.`n"
<#
╔═════════════════════════════════════════════════════════════════════════════════╗
║ If the system hosts file has been installed or update then flush the DNS cache. ║
╚═════════════════════════════════════════════════════════════════════════════════╝
#>
try {
" Attempting to flush the DNS cache."
ipconfig /flushdns
} catch {
&$WriteStatus $(
" Could not flush the DNS cache.`n" + $_.Exception.Message + "`n"
) -IsError
exit 9
}
&$WriteStatus " Successfully flushed the DNS cache.`n"
exit 0