Why Can’t I Set DNS Servers in My PowerShell Script?

0
12
Asked By CuriousCoder123 On

Hey everyone, I'm having a bit of a meltdown here. I'm writing a PowerShell script that reads the current DHCP address, finds the first available IP in the range by adding one, and then sets up a static IP. It's working fine except for the part where I try to set the DNS servers.

Here's what I've got:
```powershell
Remove-NetIPAddress -InterfaceIndex $($adapter.InterfaceIndex) -Confirm:$false
New-NetIPAddress -InterfaceIndex $($adapter.InterfaceIndex) -IPAddress $($FirstIP) -PrefixLength $(ConvertTo-IPv4MaskBits $($adapter.IPSubnet)) -DefaultGateway $($adapter.DefaultIPGateway)
Set-DnsClientServerAddress -InterfaceIndex $($adapter.InterfaceIndex) -ServerAddresses $($dnsservers)
write-host "Set-DnsClientServerAddress -InterfaceIndex $($adapter.InterfaceIndex) -ServerAddresses $($dnsservers)"
```

When I run this in ISE (as an admin), the IP, subnet, and gateway are set correctly, but the DNS servers just won't apply. I even tried copying the command from the output and pasting it directly into the terminal, and that worked perfectly fine!

Could someone shed some light on why the command isn't working when using the variables, but does when echoed? Any help would be super appreciated!

3 Answers

Answered By TechieTom87 On

It sounds like you might be running into issues with ISE, which can behave unpredictably at times. Also, you shouldn't need to encapsulate the `$dnsservers` variable in quotes. Check the type of `$dnsservers` with `$dnsservers.gettype()` to see what’s really going on. That might give you a clue!

CuriousCoder123 -

Thanks for the tip! I realized I was mistakenly treating it as a string instead of an array. Once I switched to using an array format, everything worked perfectly!

Answered By ScriptingNinja99 On

Definitely seems like it's related to how you're using the array. Make sure you provide it correctly in your command. For example, `Set-DnsClientServerAddress -InterfaceIndex 12 -ServerAddresses ("10.0.0.1","10.0.0.2")` shows the proper usage!

CuriousCoder123 -

Ahh, that was the exact insight I needed! I had no idea it required an array. Thanks a ton for pointing that out—now my script is running smoothly!

Answered By NetworkNerd55 On

Just a thought, shouldn't your DHCP server handle assigning DNS servers instead of you manually setting a static IP in the DHCP range? Seems like it could complicate things down the road!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.