Techibee.com

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.

Exit mobile version