Monday, 17 September 2012

Set Default Gateway using PowerShell

A few days back there were some networking changes in our environment that necessitated setting the default gateway for some test servers that did not have a default gateway set.

I thought there must be a way of doing this with PowerShell so that I don't have to do it on every server, turns out there is:
$nics = Get-WmiObject -Class win32_networkAdapterconfiguration -ComputerName test1,test2 | where {-not($_.DefaultIPGateway) -and $_.IPEnabled -eq "True" }
foreach ($nic in $nics) {$nic.SetGateways("")}
The  IPEnabled is there so that only IPEnabled devices show up, otherwise loads of devices appear. Ensure that you respect Capitalization of True.
test1 and test2 are two of my test servers, as long as the RPC server on those servers is responding and you have the right permissions this should work.

Annoyingly, there does not seem to be an easy way of backing out the change, after a bit of searching I found this rather unsatisfying method of enabling dhcp and then enabling static again:
foreach ($nic in $nics ) {


No comments:

Post a Comment