Skip to content

New-NetworkRoute

Windows: Creates a new IP route in the routing table

#Requires -Version 5.1
#Requires -Modules NetTCPIP

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

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

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

    [int]$RouteMetric = 1,

    [string]$ComputerName = $env:COMPUTERNAME,

    [pscredential]$Credential
)

Process {
    try {
        $session = $null
        $routeParams = @{
            'DestinationPrefix' = $DestinationPrefix
            'NextHop'           = $NextHop
            'InterfaceAlias'    = $InterfaceAlias
            'RouteMetric'       = $RouteMetric
            'ErrorAction'       = 'Stop'
        }

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

        New-NetRoute @routeParams

        $result = [PSCustomObject]@{
            DestinationPrefix = $DestinationPrefix
            NextHop           = $NextHop
            InterfaceAlias    = $InterfaceAlias
            ComputerName      = $ComputerName
            Action            = "RouteCreated"
            Status            = "Success"
            Timestamp         = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        }

        Write-Output $result
    }
    catch {
        throw
    }
    finally {
        if ($null -ne $session) {
            Remove-CimSession $session
        }
    }
}

Specifies the destination prefix of the route (e.g., "192.168.10.0/24").

Specifies the IP address of the next hop (gateway) for this route.

Specifies the friendly name of the network interface to use.

Specifies the integer metric for the route.

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.