RandyMcKay
RandyMcKay

Reputation: 326

PowerShell: add new route based on dynamic Interface index

I have a daily procedure of running route print to find Interface Index for new VPN connection and then doing ROUTE ADD {IP} MASK {MASK} IF {InterfaceIndex}.

I think it could be better a single script in PowerShell.

There in PS I can run: Get-NetIPInterface -InterfaceAlias "{InterfaceAlias}" that returns ifIndex.

Then I am not sure. Is it New-NetRoute I need to run? And how do I feed IfIndex there with IP and MASK?

Upvotes: 1

Views: 2001

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25031

You may do the following to add a non-persistent route:

$InterfaceAlias = '{InterfaceAlias}'
$Params = @{
    InterfaceAlias = $InterfaceAlias
    NextHop = (Get-NetIPConfiguration -InterfaceAlias $InterfaceAlias).IPv4DefaultGateway.NextHop
    AddressFamily = 'IPv4'
    DestinationPrefix = '{IP}/{NetworkBits}' # Example: 192.168.100.0/24
    PolicyStore = 'ActiveStore'
}
$null = New-NetRoute @Params
Get-NetRoute @Params

Explanation:

  • Splatting is used here (@Params) simply to make the *-NetRoute commands more readable.
  • You only need to update $InterfaceAlias with your interface name and update DestinationPrefix using CIDR notation.
  • $null = is used to suppress the output of New-NetRoute and can be removed if you want to see the output.
  • If you want the route to persist across reboots, then remove the PolicyStore = 'ActiveStore' line. By default, the New-NetRoute command adds the route to the Active Store (not persistent) and the Persistent Store.
  • Accessing the .IPv4DefaultGateway of the Get-NetIPConfiguration $InterfaceAlias command, returns the NextHop property needed for New-NetRoute.
  • Interface aliases can be shared across multiple indexes. You see this when you have IPv4 and IPv6 enabled. A difference between an IPv4 and IPv6 common interface alias is the interface index. Since we are specifically targeting the IPv4 family of addresses in our commands, we don't need to specify or query for the index.

Note: The New-NetRoute command must be run as admin.

Additional Considerations:


In case you are not comfortable with CIDR notation, you can use the following, which will allow using the network mask.

$InterfaceAlias = '{InterfaceAlias}'
$DestinationNetwork = '{DestinationIP}' # 192.168.200.0 for example
$Mask = '{MASK}' # 255.255.255.0 for example

$CIDR = "{0}/{1}" -f $DestinationNetwork,(-join ($Mask -split '\.' |% {[convert]::ToString($_,2).Trim('0')})).Length
$Params = @{
    InterfaceAlias = $InterfaceAlias
    NextHop = (Get-NetIPConfiguration -InterfaceAlias $InterfaceAlias).IPv4DefaultGateway.NextHop
    AddressFamily = 'IPv4'
    DestinationPrefix = $CIDR
    PolicyStore = 'ActiveStore'
}
$null = New-NetRoute @Params
Get-NetRoute @Params

Explanation: Here just update $InterfaceAlias, $DestinationNetwork, and $Mask for your situation.

Upvotes: 4

Related Questions