Home > PowerShell > PowerShell: Assign static IP address

PowerShell: Assign static IP address

Assigning a static IP address is one common task that system administrators do after building a server. In today’s post I am providing a powershell function(Set-StaticIP) which takes IP address, subnet mask, default gateway and DNS servers as parameters and assigns it to the computer where you are executing the function.

function Set-StaticIP {
<# .Synopsis Assings a static IP address to local computer. .Description Assings a static IP address to local computer. .Parameter IPAddress IP Address that you want to assign to the local computer. .Parameter Subnetmask Subnet Mask that you want to assign to the computer. This is optional. If you don't specify anything, it defaults to "255.255.255.0". .Parameter DefaultGateway Default Gateway IP Address that you want to assign to the local computer. .Parameter DNSServers DNS servers list that you want to configure in network connection properties.     .Example Set-StaticIP -IPAddress 10.10.10.123 -DefaultGateay 10.10.10.100 -DNSServers 10.10.10.120,10.10.10.121             .Notes NAME:      Set-StaticIP AUTHOR:    Sitaram Pamarthi Website:   www.techibee.com #>
[CmdletBinding()]
param (            

        [alias('IP')]
        [Parameter(mandatory=$true)]
        [string]$IPAddress,            

        [alias('Sb')]
        [Parameter(mandatory=$false)]
        [string]$Subnetmask = "255.255.255.0",            

        [alias('Gateway')]
        [Parameter(mandatory=$true)]
        [string]$DefaultGateway,            

        [alias('DNS')]
        [parameter(mandatory=$false)]
        [array]$DNSservers            

)            

Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPenabled=TRUE" | % {            

    Write-host "Trying to set IP Address on $($_.Description)"
    $_.EnableStatic($IPAddress,$Subnetmask) | out-null
    $_.SetGateways($DefaultGateway)  | out-null
    $_.SetDNSServerSearchOrder($DNSServers)  | out-null
}            

if($?) {
    write-host "IP Address set successfully"
} else {
    write-host "Static IP assignment failed"
}
}

Above simple function assigns the IP address and displays the output of execution.

Feel free to post here if you have any questions about the script.

Happy learning.

No related content found.

  1. jack
    July 17, 2011 at 11:27 pm | #1

    helpful post

  2. Johan
    August 9, 2011 at 8:12 pm | #2

    Cheers, just what I was looking for!

  1. No trackbacks yet.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>