Reputation: 326
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
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:
@Params
) simply to make the *-NetRoute
commands more readable.$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.PolicyStore = 'ActiveStore'
line. By default, the New-NetRoute
command adds the route to the Active Store (not persistent) and the Persistent Store..IPv4DefaultGateway
of the Get-NetIPConfiguration $InterfaceAlias
command, returns the NextHop
property needed for New-NetRoute
.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