Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Powershell: Change DNS IP addresses remotely on multiple computers using CIM & WMI

Although I had written this script around 4 years back I have again revised it to work it in more better way with status report on console. I used this script again after long time to change/update DNS ip addresses on remote Windows servers, after introducing my new upgraded DNS servers. Same task I performed but this time  to replace DNS ips on an average 6000 remote windows servers. As it can be seen in below screenshot, There are 2 Nics In my environment, on all the server and I wanted to change DNS IPs on physical adapter with name Ethernet only. 

If you check on windows 2012 and above server OS, physical network adapter is named as Ethernet by default, unless it is modified.

Windows Powershell Network Connections physical adapter Ethernet properties Internet Protocol version 4 tcpipv4 dns server addreses preferred dns

Copy script in the Set-DnsIP.ps1 file, I have kept file on root c:\ drive. Run Set-ExecutionPolicy Unrestricted, so ps1 scripts are allowed to execute. Next by running below command I will replace existing DNS IPs and it also verify it and shows result on console. For simplicity I am running this command directly from domain joined server logged in with domain admin username and password, So there is no requirement to mention credentials.
.\Set-DnsIP.ps1 -Name DSC01 -NetworkName Ethernet -DnsIPs @('192.168.33.5','192.168.33.6')

PARAMETERS
-Name = Put computername here
-NetworkName = Type network physical adapter name here which is found under network connections, in most of the cases it will named as Ethernet.
-DnsIP = here you can put multiple ip in array with @()
-Protocol = This is optional and Dcom (Remote procedure call - RPC) or WSman (Windows Powershell remoting need to be enabled) can be used here. By default it connects using Dcom and does not require any special configuration.
-Credential = This is another optional parameter and here you can add credentials to connect remotely or locally.

Another way of performing same task on multiple system, Here in below example I am fetching computer names from active directory domain controller and updating IP on those servers with foreach loop.

Get-ADComputer -Filter * | foreach {.\Set-DNSIP -Name $_.Name -NetworkName Ethernet -DnsIPs 192.168.33.11}

Powershell set dns IP remotely or locally Set-DnsIP Ethernet Physical adapter DnsIp, Get-ADComputer successful completion

In the last if you have list of servers in plain text file replace Get-Adcomputer -filter * with cat filename.txt. This script is based and built using CIM cmdlets.

to use different username and password credentials than the logged in user, use parameter -credential, it will popup for username and password.
.\Set-DnsIP.ps1 -Name DSC01 -NetworkName Ethernet -DnsIPs @('192.168.33.5','192.168.33.6') -Credential

  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
#requires -version 3
<#
.SYNOPSIS
    Set or change DNS IP address in network adapter.
.DESCRIPTION
    The Set-DnsIP cmdlet changes DNS IP addresses of a local or remote etherenet card on windows. It requires parameternames computername, Ethernet Name, DNS IP addresses. This cmdlet uses CIM and WMI (DCom and winrm) protocol to connect remote computer. 
.PARAMETER Name
    Prompts you for local or remote computer hostname, Computername parameter is an alias, This value can be taken from pipline by property name.
.PARAMETER NetworkName
    This is physical network adapter name on the windows server or desktop, By default 2012 and above windows OS network name is Ethernet.
.PARAMETER DnsIPs
    This sets DNS Ip addresses, multiple DNS servers can be provided with this parameters.
.PARAMETER Protocol
    There are two protocols can be used while connecting to remote computer, first is DCOM which is default and need not to mention, Default will work in all scenario. Another protocol is WSman require PS remoting need to be enabled. 
.INPUTS
    No Input
.OUTPUTS
    Output is on console directly.
.NOTES
  Version:        2.0
  Author:         Kunal Udapi
  Creation Date:  12 February 2017
  Purpose/Change: Update to my existing script buit on 1 June 2013 (http://kunaludapi.blogspot.in/2013/06/change-dns-ip-address-remotely-on.html)
  Useful URLs: http://vcloud-lab.com/entries/powershell/powershell-ps-remoting-between-standalone-workgroup-computers
.EXAMPLE 1
    PS C:\>Set-DNSIP -Name MyServer01 -NetworkName Ethernet -DnsIPs @('192.168.33.5', '192.168.33.6')

    This command sets DNS ips on computername 'MyServer01'. Physical Adapter name is 'Ethernet'. IP addresses can be mentioned in arrays.
.Example 2
    Get-ADComputer -Filter * | ForEach-Object {Set-DNSIP -Name $_.Name -NetworkName Ethernet -DnsIPs 192.168.33.11}

    Here computer names are pulled from active directory computers. Process further with Foreach-Object loop.
.EXAMPLE 3
    PS C:\>Set-DNSIP -Name MyServer01 -NetworkName Ethernet -DnsIPs 192.168.33.11 -Protocol Wsman

    With optional parameter name 'Protocol', DCom and WSMan protocol can be used, Dcom is default protocol and works in every scenario, for WSman Ps remoting need to be enabled and check notes help section for more information.
#>

[CmdletBinding(SupportsShouldProcess=$True,
    ConfirmImpact='Medium',
    HelpURI='http://vcloud-lab.com')]
Param
(
    [parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
    [alias('ComputerName')]
    [String]$Name = 'Localhost',
    [parameter(Position=1, Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
    [alias('LAN', 'EthernetName')]
    [String]$NetworkName = 'EtherNet',
    [parameter(Position=2, Mandatory=$true, 
        ValueFromPipeline=$true)]
    [array]$DnsIPs = @('192.168.33.5','192.168.33.6'),
    [parameter(Position=3, Mandatory=$false)]
    [ValidateSet('Dcom','Default','Wsman')]
    [String]$Protocol = 'Dcom',
    [Switch]$Credential
)
Begin {
    $CimSessionOptions = New-CimSessionOption -Protocol $Protocol
    $Query = "Select * from  Win32_NetworkAdapter" #Where NetConnectionID='$NetworkName'"

    if (-not(Test-Connection -ComputerName $Name -Count 2 -Quiet)) {
        Write-Host -BackgroundColor DarkYellow ([char]8734) -NoNewline
        Write-Host " $Name is not reachable but still trying to connect...."
        #Break
    }
    else {
        Write-Host -BackgroundColor DarkGreen ([char]8730) -NoNewline
        Write-Host " $Name is reachable connecting...."
    }
}
Process {
    try {
        if ($Credential.IsPresent -eq $false) {
            $Cimsession = New-CimSession -Name $Name -ComputerName $Name -SessionOption $CimSessionOptions -ErrorAction Stop
        }
        else {
            $Cred = Get-Credential -Message 'Type Your credentials to connect remotely' -UserName (WhoAmI)
            $Cimsession = New-CimSession -Name $Name -ComputerName $Name -SessionOption $CimSessionOptions -Credential $Cred -ErrorAction Stop
        }
        $AllNICs = Get-CimInstance -Namespace 'root/CIMv2' -Query $Query -CimSession $Cimsession
        if ($AllNICs.NetConnectionID -contains $NetworkName) {
            $Nic = $AllNICs | Where-Object {$_.NetConnectionID -eq $NetworkName}
            $NICConf = Get-CimAssociatedInstance -InputObject $NIC -ResultClass Win32_NetworkAdapterConfiguration -CimSession $Cimsession
            $NICConfituraion = $NICConf | Invoke-CimMethod -MethodName SetDNSServerSearchOrder -Arguments @{DNSServerSearchOrder = $DnsIPs}
            $NICConf = Get-CimAssociatedInstance -InputObject $NIC -ResultClass Win32_NetworkAdapterConfiguration -CimSession $Cimsession
            $errorcode = $NICConfituraion.ReturnValue
        }
        else {
            Write-Host -BackgroundColor DarkRed ([char]215) -NoNewline
            Write-Host " Connected to $Name successfully but no NIC found with name $NetworkName"
        }
    }
    catch {
        Write-Host -BackgroundColor DarkRed ([char]215) -NoNewline
        Write-Host " DNS IP on $Name did not changed, check manually." 
        $errorcode = -1
    }
}
end{
    switch ($errorcode) { 
        -1 {Write-host -NoNewline ''}
        0 {Write-Host -BackgroundColor DarkGreen ([char]8730) -NoNewline; " Successful completion, no reboot required, New DNS IPs are $($NICConf.DNSServerSearchOrder -join ', ')"; break}
        1 {'Successful completion, reboot required'; break}
        64 {'Method not supported on this platform'; break}
        65 {'Unknown failure'; break}
        66 {'Invalid subnet mask'; break}
        67 {'An error occurred while processing an Instance that was returned'; break}
        68 {'Invalid input parameter'; break}
        69 {'More than 5 gateways specified'; break}
        70 {'Invalid IP address'; break}
        71 {'Invalid gateway IP address'; break}
        72 {'An error occurred while accessing the Registry for the requested information'; break}
        73 {'Invalid domain name'; break}
        74 {'Invalid host name'; break}
        75 {'No primary/secondary WINS server defined'; break}
        76 {'Invalid file'; break}
        77 {'Invalid system path'; break}
        78 {'File copy failed'; break}
        79 {'Invalid security parameter'; break}
        80 {'Unable to configure TCP/IP service'; break}
        81 {'Unable to configure DHCP service'; break}
        82 {'Unable to renew DHCP lease'; break}
        83 {'Unable to release DHCP lease'; break}
        84 {'IP not enabled on adapter'; break}
        85 {'IPX not enabled on adapter'; break}
        86 {'Frame/network number bounds error'; break}
        87 {'Invalid frame type'; break}
        88 {'Invalid network number'; break}
        89 {'Duplicate network number'; break}
        90 {'Parameter out of bounds'; break}
        91 {'Access denied'; break}
        92 {'Out of memory'; break}
        93 {'Already exists'; break}
        94 {'Path, file or object not found'; break}
        95 {'Unable to notify service'; break}
        96 {'Unable to notify DNS service'; break}
        97 {'Interface not configurable'; break}
        98 {'Not all DHCP leases could be released/renewed'; break}
        100 {'DHCP not enabled on adapter'; break}
        default {'Other - Error code 101–4294967295'; break}
    }
}

Go Back



Comment

Blog Search

Page Views

12278737

Follow me on Blogarama