Search code examples
powershelldnsdhcp

PowerShell- Add Multiple DNS Servers to New DHCP Scope


I am trying to create some new DHCP scopes with PowerShell but I'm stuck when adding our 3 DNS servers to Option 3. I have a CSV file with all of the information and the DNS fields that I've tried are:

DNS - 1.1.1.1, 2.2.2.2, 3.3.3.3

DNS1 - 1.1.1.1

DNS2 - 2.2.2.2

DNS3 - 3.3.3.3

Import-Csv "C:\temp\DHCP.csv" | % {
Add-DhcpServerv4Scope -StartRange $_.StartRange -EndRange $_.EndRange -SubnetMask $_.SubnetMask -Name $_.ScopeName -cn $_.DHCPServer -Description $_.Description -LeaseDuration $_.LeaseDuration -State Active -WhatIf
If ($_.Router -notlike "") {
Set-DhcpServerv4OptionValue -cn $_.DHCPServer -ScopeId $_.ScopeID -OptionId 3 $_.Router -WhatIf }
If ($_.TimeServer -notlike "") {
Set-DhcpServerv4OptionValue -cn $_.DHCPServer -ScopeId $_.ScopeID -OptionId 4 $_.TimeServer -WhatIf }
If ($_.DNS -notlike "") {
$DNSString=$_.DNS1 + ", " + $_.DNS2  + ", " + $_.DNS3
#Set-DhcpServerv4OptionValue -cn $_.DHCPServer -ScopeId $_.ScopeID -DnsServer $DNS -WhatIf }
Set-DhcpServerv4OptionValue -cn $_.DHCPServer -ScopeId $_.ScopeID -OptionID 3 $DNSString -WhatIf }

Any idea how to set multiple DNS Servers in a DHCP scope with PowerShell? Any help would be greatly appreciated. Thanks.

Kyle


Solution

  • Three things stand out to me:

    1. Option 3 is for setting a router, not DNS servers.
    2. Set-DhcpServerv4OptionValue has a special parameter for setting DNS servers, so you don't need to know the Option ID
    3. The parameter takes an array, instead of a string with commas in it.

    Issue 1

    You want Option 6 for DNS (don't use Option 5). But again, see 2.

    Issue 2

    Ignore the -OptionID parameter and use -DnsServer instead.

    Issue 3

    This parameter is an array type, so supply the values as an array.

    Possibly working code:

    $dnsArray = $_.DNS1,$_.DNS2,$_.DNS3
    Set-DhcpServerv4OptionValue -ComputerName $_.DHCPServer -ScopeId $_.ScopeID -DnsServer $dnsArray
    

    Edit

    Since you're doing this in bulk, you may want to use -Force, which skips DNS server validation.