Skip to content

Set-IPAddressStatic

Windows: Configures a static IP address for a network adapter

#Requires -Version 5.1
#Requires -Modules NetTcpIp

[CmdletBinding()]
Param
(
    [Parameter(Mandatory = $true)]
    [string]$Name,

    [Parameter(Mandatory = $true)]
    [string]$IPAddress,

    [Parameter(Mandatory = $true)]
    [int]$PrefixLength,

    [string]$DefaultGateway,

    [string]$ComputerName = $env:COMPUTERNAME,

    [pscredential]$Credential
)

Process
{
    try
    {
        $session = $null
        $cimParams = @{
            'ErrorAction' = 'Stop'
        }

        if ($ComputerName -ne $env:COMPUTERNAME)
        {
            $sessionParams = @{
                'ComputerName' = $ComputerName
            }
            if ($null -ne $Credential)
            {
                $sessionParams.Add('Credential', $Credential)
            }
            $session = New-CimSession @sessionParams
            $cimParams.Add('CimSession', $session)
        }

        # Identify the interface
        $interface = Get-NetIPInterface -InterfaceAlias $Name -AddressFamily IPv4 @cimParams
        
        # Remove existing IPv4 addresses to avoid conflicts
        Get-NetIPAddress -InterfaceIndex $interface.InterfaceIndex -AddressFamily IPv4 @cimParams | Remove-NetIPAddress -Confirm:$false @cimParams

        # Configure static IP
        $newAddressParams = @{
            'InterfaceIndex' = $interface.InterfaceIndex
            'IPAddress'      = $IPAddress
            'PrefixLength'   = $PrefixLength
            'AddressFamily'  = 'IPv4'
        }
        if (-not [string]::IsNullOrWhiteSpace($DefaultGateway))
        {
            $newAddressParams.Add('DefaultGateway', $DefaultGateway)
        }
        
        New-NetIPAddress @newAddressParams @cimParams | Out-Null

        # Return the new configuration
        $result = Get-NetIPAddress -InterfaceIndex $interface.InterfaceIndex -AddressFamily IPv4 @cimParams | Select-Object InterfaceAlias, IPAddress, PrefixLength, AddressFamily
        Write-Output $result
    }
    catch
    {
        throw
    }
    finally
    {
        if ($null -ne $session)
        {
            Remove-CimSession $session
        }
    }
}

Specifies the name or alias of the network adapter to configure.

Specifies the static IPv4 address to assign.

Specifies the subnet prefix length (e.g., 24 for 255.255.255.0).

Specifies the default gateway IP address.

Specifies the name of the target computer. Defaults to the local computer.

Specifies a PSCredential object for remote connection.

An interactive directory of PowerShell scripts.