forked from imabdk/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Change-DNSServers.ps1
72 lines (68 loc) · 2.86 KB
/
Change-DNSServers.ps1
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
<#
.SYNOPSIS
Set or change configured DNS server addresses. Something I created as I needed to change DNS servers on a large scale of servers.
Intended to be used with ConfigMgr for automation purposes.
.DESCRIPTION
Same as above
.NOTES
Filename: Change-DNSServers.ps1
Version: 1.0
Author: Martin Bengtsson
Blog: www.imab.dk
Twitter: @mwbengtsson
.LINK
https://www.imab.dk/set-primary-and-secondary-dns-server-addresses-using-configmgr-and-powershell/
#>
param(
[Parameter(Mandatory=$true)]
[string]$primDNS,
[Parameter(Mandatory=$true)]
[string]$secDNS,
[Parameter(Mandatory=$false)]
[string]$addressFam = "IPv4"
)
begin {
function Get-InterfaceIndex() {
# Finding net adapters which is Up and ConnectorPresent is TRUE
$netAdaptUp = Get-NetAdapter | Where-Object {$_.Status -eq "Up" -AND $_.ConnectorPresent -eq $True}
if (-NOT[string]::IsNullOrEmpty($netAdaptUp)) {
Write-Output $netAdaptUp.ifIndex
Write-Output $netAdaptUp.InterfaceDescription
}
}
function Change-DNSServers($fIfIndex,$fAddressFam,$fPrimDNS,$fSecDNS) {
# Setting the primDNS and secDNS to 0 will result in a reset to default DNS server addresses
if (($primDNS -eq 0) -OR ($secDNS -eq 0)) {
Write-Verbose -Verbose -Message "priDNS and secDNS is null. Resetting DNS server addresses to default on $global:ifDescription"
try {
Set-DnsClientServerAddress -InterfaceIndex $fIfIndex -ResetServerAddresses
}
catch {
Write-Verbose -Verbose -Message "Failed to run -ResetServerAddresses"
}
}
else {
$currentDNS = Get-DnsClientServerAddress -AddressFamily $fAddressFam -InterfaceIndex $fIfIndex | Where-Object {$_.ServerAddresses -notcontains $fPrimDNS}
if (-NOT[string]::IsNullOrEmpty($currentDNS)) {
try {
Set-DnsClientServerAddress -InterfaceIndex $fIfIndex -ServerAddresses ("$fPrimDNS","$fSecDNS")
Write-Verbose -Verbose -Message "successfully changed the DNS servers on $global:ifDescription to primDNS: $primDNS and secDNS: $secDNS"
}
catch {
Write-Verbose -Verbose -Message "Failed to change the DNS servers on $global:ifDescription"
}
}
else {
Write-Verbose -Verbose -Message "No changes to DNS on $global:ifDescription required. Doing nothing."
}
}
}
}
process {
$ifIndex = (Get-InterfaceIndex)[0]
$global:ifDescription = (Get-InterfaceIndex)[1]
Change-DNSServers -fIfIndex $ifIndex -fAddressFam $addressFam -fPrimDNS $primDNS -fSecDNS $secDNS
}
end {
#Nothing to see here
}