Saturday, June 2, 2012

Set IP Address via Powershell

I wanted to script a complete install from powershell for my lab enviroment.  So I knew i had to start with some plain old fashion calls to wmi and whatnot.  So I ended up googling it and came across Andy's post over at wordpress http://getpowershell.wordpress.com/2008/08/13/powershell-function-set-ipaddress/

So easily read and cleanly coded I wanted to share here as well, the only modifications that I changed was adding the requirement that parameters that have to be specified and out-null some responses.:



function Set-IPAddress {
param(  
[parameter(Mandatory = $true)][string]$networkinterface,
[parameter(Mandatory = $true)][string]$ip,
[parameter(Mandatory = $true)][string]$mask,
[parameter(Mandatory = $true)][string]$gateway,
[parameter(Mandatory = $true)][string]$dns1,
[string]$dns2,
[string]$registerDns = "TRUE"
)


$dns = $dns1
if($dns2){$dns ="$dns1,$dns2"}
$index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex
$NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index}|out-null
$NetInterface.EnableStatic($ip, $mask)|out-null
$NetInterface.SetGateways($gateway)|out-null
$NetInterface.SetDNSServerSearchOrder($dns)|out-null
$NetInterface.SetDynamicDNSRegistration($registerDns)|out-null
}



No comments:

Post a Comment