Как добавить статический маршрут с помощью комндлета power shell

Windows · December 16, 2023

Mastering Network Configuration with PowerShell: Get-NetRoute Command

Understanding the Get-NetRoute Command

The Get-NetRoute command is a part of the NetTCPIP module in PowerShell, which comes with a suite of cmdlets for network configuration and management. This command retrieves information about the IP routing table on a Windows operating system, which is crucial for troubleshooting and configuring network settings on your VPS or local machine.

Why Use Get-NetRoute?

Understanding the routes on your network can help you diagnose connectivity issues, plan your network layout, and secure your network by ensuring that traffic is flowing through the correct paths. The Get-NetRoute command provides a snapshot of how packets are directed through the network, allowing you to make informed decisions about routing configurations.

Using Get-NetRoute: Examples and Code Samples

Let’s dive into some practical examples of how to use the Get-NetRoute command to manage your network routes effectively.

Basic Usage

Get-NetRoute

This command will display all the routes in the IP routing table. The output includes information such as the destination prefix, next hop (gateway), route metric, and interface index.

Filtering Routes by Destination

Get-NetRoute -DestinationPrefix '192.168.1.0/24'

This command filters the routing table to show only routes that pertain to the specified destination prefix. This is useful when you want to focus on a particular subnet or IP range.

Viewing Routes for a Specific Interface

Get-NetRoute -InterfaceIndex 12

By specifying the InterfaceIndex parameter, you can retrieve routes associated with a particular network interface. This is particularly useful when your host has multiple network interfaces, and you need to manage routes for each one separately.

Sorting Routes by Metric

Get-NetRoute | Sort-Object RouteMetric

This command sorts the routes based on their metric, which determines the priority of the routes. Lower metrics have higher priority. Sorting by metric can help you understand the preferred paths for network traffic.

Advanced Usage of Get-NetRoute

Adding a Persistent Route

New-NetRoute -DestinationPrefix '10.10.0.0/16' -InterfaceIndex 12 -NextHop '192.168.1.1' -RouteMetric 10 -PolicyStore PersistentStore

This example shows how to add a new persistent route to the routing table. Persistent routes remain in the table even after a system reboot, which is essential for permanent network configurations on your cloud infrastructure.

Removing a Route

Remove-NetRoute -DestinationPrefix '10.10.0.0/16' -Confirm:$false

This command removes a route from the routing table without prompting for confirmation. Be cautious when using this command, as removing routes can affect network connectivity.

Conclusion: Key Takeaways of Using Get-NetRoute

In summary, Get-NetRoute is essential for:

  • Diagnosing connectivity issues
  • Planning network layouts
  • Ensuring traffic flows through intended paths
  • Adding, modifying, and removing routes as needed

By mastering the Get-NetRoute command, you can take full control of your network routing and maintain a robust hosting environment for your applications and services. Remember to always test changes in a controlled environment before applying them to production systems to prevent any unintended disruptions.

In my router there is a fallback setting which routes all traffic via mobile data if jitter of my cable isp is to high. How can i periodically check with powershell which isp (which route) is currently active?

I get the next hops via pathping, but i’m not able to extract the output. Maybe there is a better way?

asked Aug 4, 2023 at 19:32

Steffen's user avatar

  • Would a simple “what’s my ip” check work? Presumably the different ISP routes will present on different IP ranges (although maybe too many distinct ranges to useful?), but something like Invoke-WebRequest -Uri "https://api.ipify.org/" would potentially give you a pointer. Failing that, does your router have an API you can query to pull the current status (knowing the make / model would hel)?

    Aug 4, 2023 at 19:49

  • No, theres unfortunatly no API at the router. Your solution works great if all traffic is routed in the same way. In my case the script should run on the PBX which have special routing settings. So, die SIP traffic could be routed via mobile and all other traffic is routed via cable.

    Aug 4, 2023 at 20:06

  • Could you run the script on a client instead that sends traffic via the SIP route? Or configure the network settings somehow for whatever session is hosting PowerShell on the router to use the SIP route (assuming it isn’t already – but if you’re using pathping to test the active route it’s presumably already using the SIP / mobile route otherwise the output would always show the cabled route)?

    Aug 4, 2023 at 20:15


Load 7 more related questions


Show fewer related questions

How to add a static route using a PowerShell cmdlet

Since static routes do not take part in any kind of automatic discovery process, it is very easy to manage and configure them. A list of potential destinations can be generated using a static route by combining the network address of the destination with the subnet mask. Static routes are very straightforward. The Windows operating system comes equipped with an internal routing table that gives it the ability to select appropriate paths for data transmission.

The process of taking a packet from one device and transmitting it through the network to another device that is connected to a different network is referred to as routing. When sending packets through a routed network, the first step is to use the logical network address of the host that the packets are destined for. After that, the hardware address of the host, also known as the MAC address, is used to ensure that the packet is sent to the correct destination host.

What is a routing device and how does the process of routing work?

When a data packet is received by a network, the router immediately begins to read the headers, which include information regarding the packet’s ultimate destination. After that, it compares the information with the entries in the routing table (which is a list of objectives) and chooses which route is the most efficient to take to go to the desired location. In the end, the router will propose a route for the packets to take, which will involve passing through several other routers on the way to the destination node.

Security concerns

Because security concerns prevent some routes from being added to the default gateway device, you will need to make use of an additional routing device to carry out certain operations. In such a scenario, it is possible to configure a nearby Windows machine so that it can carry out the necessary routing functions.

VLANs or subnets

On your network, you have created many subnets or VLANs, and now you need to route traffic to one of those subnets in particular. Testing these kinds of setups can be made significantly easier with the utilization of static routes.

Trafficking purposes

You want to have better control of the routing table and the flow of traffic coming into and going out of your network. You are currently utilizing a Windows PC as a router for your network.

What is meant by the term “Routing Table”?

Before a device on a network may transfer data to another device on the same network, the device must first determine where the data should be sent. If the network device is unable to establish a direct connection with the device to which it is sending data, the data will be relayed to the destination device via a series of intermediary devices. Each device needs to keep track of which direction to transport different packets of data, and to do so, it makes use of something that we refer to as a routing table.

  1. In the search bar provided by Windows, type “powershell” to locate the PowerShell application.
  2. Select the application with the right mouse button, then click “Run as administrator”.
  3. Once the PowerShell command prompt has opened, type the following command to inspect the routing table: route print.

What PowerShell cmdlet can be used to add a static route?

Managing static routes in the routing table is the responsibility of the ip-route command. It is necessary to issue this command for each static route that you wish to add to the routing database. Use the no ip-route command if you want to get rid of a static route. Execute this command for every static route that you want to remove from the routing table.

The Step-by-Step Guide to Adding a Static Route Using PowerShell CMDLETs

route /f /p mask metric if the condition is met

  1. /f is a command that can be used to clear the routing table.
  2. Using the /p switch will add the routing table to the network permanently. The command is a notation that is utilized to specify the command that
  3. you wish to use, such as add, change, or delete.
  4. /p add as the route 192.168.0.0 mask 255.255.0.0 192.168.0.1 if 0x2

How exactly does one go about including a Static Route in the Windows Routing Table?

  • The -f switch erases any entries in the routing table that do not host routes (routes that have a netmask of 255.255.255.255) as well as the loopback network route.
  • -p When used in conjunction with the add command, the route that you specify will be added to the registry. This route will then be used to initialize the IP routing table each time the TCP/IP protocol is started.
  • Command: Identifies the command that will be carried out. The following are examples of valid commands: (add, change, delete, print)
  • Destination: Identifies the network location where the route will ultimately end up.
  • Mask: the network destination’s netmask (also known as the subnet mask) is indicated by the netmask parameter.
  • Gateway: Identifies the IP address of the next hop, also known as the forwarding IP address, over which the group of addresses that are determined by the network destination and the subnet mask can be accessed.
  • Metric: Specifies an integer cost metric for the route, which can range anywhere from one to nine thousand and nine hundred ninety-nine. This metric is used to choose from several routes in the routing table that most closely match the destination address of a packet that is being forwarded. The path that results in the lowest metric is the one that is selected.
  • Interface: Indicates the index of the interface that the destination can be accessed through.
  1. In the search bar provided by Windows, type “powershell” to locate the PowerShell application.
  2. Select the application with your right mouse button, and then select “Run as administrator”.
  3. When the PowerShell command prompt appears, at this point you should type the following command to add the static route.

route add 10.51.0.0 mask 255.255.0.0 10.23.0.1

Static route with persistence

/p add as the route 10.51.0.0 mask 255.255.0.0 10.23.0.1

route added with 10.51.0.0, masked with 255.255.0.0, and the metric set to 65

The route that is permanently set up with an interface

When viewing the routing table using the route print command, the interface list numbers are presented shortly before the IPv4 route table. Loopback is represented by the index number 1 (0x1), and the remaining indices are distributed among the various existing network interfaces.

route add 10.51.0.0 mask 255.255.0.0 10.23.0.1 if 0x7

Conclusion

This post explained how to use PowerShell to add a static route to a routing table along with other important parameters. If you use the route print command to view the routing table, you’ll be able to see all of your static route entries, which is useful if you want to review the contents of the entries you’ve created.

We hope that at the end of this article, you will have a better understanding of the notion of a static route as well as how to build it in operating systems that use the Windows platform.

Add Static Route Using PowerShell cmdlet FAQs

What is the PowerShell cmdlet used to add a static route?

The PowerShell cmdlet used to add a static route is New-NetRoute.

What are the parameters for the New-NetRoute cmdlet?

The New-NetRoute cmdlet takes several parameters, including DestinationPrefix (the destination IP address and subnet mask), NextHop (the IP address of the next hop router), and InterfaceIndex (the index of the network interface to use).

What are some common use cases for adding a static route using PowerShell?

Some common use cases for adding a static route using PowerShell include configuring VPN connections, routing traffic between subnets, and configuring network load balancing.

What permissions are required to add a static route using PowerShell?

How can I verify that the static route has been added successfully?

You can use the Get-NetRoute cmdlet to verify that the static route has been added successfully. Alternatively, you can use the route print command in the Windows command prompt to view the routing table.

Is it possible to remove a static route using PowerShell?

Yes, you can use the Remove-NetRoute cmdlet to remove a static route that has been added using PowerShell.

Can I add multiple static routes at once using PowerShell?

Yes, you can add multiple static routes at once using PowerShell by using a loop or by specifying multiple DestinationPrefix and NextHop values in a single command.

Are there any limitations to adding static routes using PowerShell?

The New-NetRoute cmdlet only supports IPv4 routes. If you need to add an IPv6 static route, you will need to use the Add-NetRoute cmdlet instead. Additionally, some network adapters may not support all of the parameters of the New-NetRoute cmdlet, so it is important to verify that the adapter supports the required parameters before attempting to add a static route.

Windows · December 16, 2023

What is Get-NetRoute?

Get-NetRoute is a PowerShell command that retrieves information about the IP routing table on a computer. The routing table is a set of rules that determines where network traffic is directed. It is essential for the proper functioning of a network, as it ensures that data packets are sent to the correct destination.

The Get-NetRoute command is part of the NetTCPIP module, which contains a set of cmdlets for managing TCP/IP networking on Windows operating systems. With Get-NetRoute, you can view the routing table, filter the results based on specific criteria, and even export the data for further analysis.

Using Get-NetRoute


PS C:> Get-NetRoute

DestinationPrefix NextHop         RouteMetric IfIndex
----------------- -------         ----------- -------
0.0.0.0/0         192.168.1.1     0           12
192.168.1.0/24    0.0.0.0         256         12
::/0              fe80::1         256         12
fe80::/64         ::              256         12


PS C:> Get-NetRoute -DestinationPrefix "192.168.1.0/24"

DestinationPrefix NextHop         RouteMetric IfIndex
----------------- -------         ----------- -------
192.168.1.0/24    0.0.0.0         256         12

Examples of Get-NetRoute in Action

Let’s look at some practical examples of how Get-NetRoute can be used in a USA VPS Hosting environment.

Example 1: Identifying the Default Gateway

One common use case for Get-NetRoute is to identify the default gateway for a server. The default gateway is the next hop for traffic that is destined for an external network. To find the default gateway, you can filter the routing table for the destination prefix 0.0.0.0/0 (IPv4) or ::/0 (IPv6).


PS C:> Get-NetRoute -DestinationPrefix "0.0.0.0/0"

DestinationPrefix NextHop         RouteMetric IfIndex
----------------- -------         ----------- -------
0.0.0.0/0         192.168.1.1     0           12

Example 2: Exporting the Routing Table

Another useful application of Get-NetRoute is exporting the routing table for documentation or analysis. You can use the Export-Csv cmdlet to save the routing table to a CSV file.


PS C:> Get-NetRoute | Export-Csv -Path "C:routing-table.csv" -NoTypeInformation

Conclusion

In this article, we’ve covered the basics of the Get-NetRoute command, provided examples of its use in a hosting environment, and shown how to export the routing table for further analysis. Whether you’re managing a single server or a complex cloud infrastructure, Get-NetRoute is an essential command to have in your toolkit.

The concept of a route is very simple, think back to the days of old telephony. To contact the desired person you would have to contact a phone operator who would physically move telephone lines to get you in contact with the other person. In essence, what the operator does is reroute your telephone line to your desired destination. The same principle is applied in computer networking as well. You use a device called a router which plays the part of the operator to properly maintain the flow of data.

Computer Routing

  • Bandwidth Bandwidth is the data transfer rate which is measured in bits per second. High transfer values such as Gb/s are preferred over lower, more archaic ones such as kb/s. Check the bandwidth capacity throughout all links in the network and the one that overall displays the highest value is the best.
  • Delay Delay specifies the latency for data to travel from one communication point to another and is measured in milliseconds. The way it is measured is either one-way or round-trip. The round-trip latency type is the preferred type since the data has to move to a specific point and then get responded to with a ping, effectively meaning you only need one point to measure it. Check the delay throughout all the links in the network and the overall lowest one is best.
  • Load Load defines the measure of which a router or network link is busy. This value can be calculated in many ways, mostly through CPU utilization and packets processed per second. Ensure that the high-traffic load values are still not stressing your system for optimal results.
  • Hop Count A hop occurs when data is passed from one communication point to the next. Your total hop count is the amount it takes for your package to go from the source to the destination. Every hop incurs additional latency so the optimal hop count will be the one with the quickest route.
  • Reliability Reliability depends on the network links themselves and how often they go down. Some networks are more stable than others, some are easily brought back up, and others are not. High reliability depends on how well you can keep up and maintain your networks.

What Is a Routing Table?

A routing table is similar to the mail system. If you want to send a letter to someone, you must first write down to who you want to send it. Then if the letter is unable to be sent directly to the recipient, it is instead moved over to multiple centers where they keep forwarding it. The same principle is applied in computing. Your data is moving across different nodes and each node needs to keep track of where to route each piece of data. The nodes can do this with the help of the routing table. The routing tables keep databases to know how to forward data.

Why Use Static Routing?

What is Powershell?

Powershell is an open-source, command-line interface made by Microsoft. It is used to automate tasks and configurations with code. A cmdlet, pronounced as command-let, is a basic, single-function command in Powershell. They can either be used singularly to perform a task or in conjunction with one another to carry out more significant functions. It is important to note that cmdlets are not written in Powershell, they are written in another language, then compiled, and only then made available.

How to View the Routing Table Using Powershell

  1. Open up windows search and look for Powershell
  2. Right-click on Powershell and make sure to run it as an administrator
  3. Once Powershell is open, run the following command “route print”

Here’s an explanation of what this syntax does step by step.

  • /f Clears the current routing table.
  • /p Adds a new routing table.
  • command You can use add, change, and delete commands depending on what you need.
  • destination Defines the destination network.
  • mask netmask Defines the subnet mask of your destination network.
  • gateway Defines the gateway IP address.
  • metric Identifies an integer cost metric.
  • if interface Defines the network interface name.

route /p add 192.168.0.1 mask 255.255.0.0 192.168.0.2 if 0x2

Now to verify that you successfully added a new static route, type in:

You should be able to see the new static route added and displayed in your routing table.

Conclusion

In this guide, we explained what a route is, and how to optimize and pick out your ideal networking route. We also explained how bandwidth, delay, load, hop count, and reliability impact your route choice. We cleared up the reasons why to use static routing over the other two types. Finally, we explained how to view and add a static route using the Powershell cmdlet. Hopefully, this guide covered the details you need to start managing your traffic.


How to Add a Static Route Using a PowerShell CMDLET

It is relatively simple to manage and set up static routes because they do not take part in any kind of autonomous route discovery procedure. By employing a static route and combining the network address of the destination with the subnet mask, it is possible to obtain a list of possible destinations to which the route could lead. Static routes are really simple to understand. The Windows operating system comes pre-installed with an internal routing table, which grants it the capacity to determine which paths are most suitable for data transfer and allows it to do so automatically.

In this post, we will just discuss static routing to understand how it operates. Additionally, adding a static route can be accomplished in a variety of methods; however, in this piece, we will discuss adding a static route by utilizing a PowerShell cmdlet.

What does Static Routing mean?

The process of routing is notoriously difficult since it requires sending each data packet over the right channels as it travels from its origin to its final destination. This is typically done based on a set of rules or protocols that determines the most optimal path for a data packet under different situations. This can be done based on a variety of different rules and protocols. A routing table is where you’ll find these rules written down.

What is meant by “Routing Table”?

Before a device on a network may transfer data to another device on the same network, the device must first determine where the data should be sent. If the network device is unable to establish a direct connection with the device to which it is sending data, the data will be relayed to the destination device via a series of intermediary devices. Each device needs to keep track of which direction to transport different packets of data, and to do so, it uses something that we refer to as a routing table.

Regarding the delivery of packages, a routing table is similar to a distribution map. It is a database that, like a map, keeps track of paths and uses these to decide when traffic leaves a routing device, whether that device is an actual router or a personal computer. It uses the paths to determine which way to forward traffic. Before making any modifications to your existing routing table, it is vital to first review the table in its current state.

What exactly is contained within a Routing Table?

The IP address of the location to which a data packet will be delivered once it has been sent over a network.

  • Destination: The IP address to which a data packet is transferred over a network.
  • Next hop: The closest or following IP address to which the data packet is sent. The following hop address is calculated based on the routing protocol and its metrics.
  • Interface: This shows the local network interface that the device must follow to forward the packet from its origin to the next hop or the main gateway. The main gateway is the final destination for all packets.
  • Metric: It shows the costs of all possible routes, which is useful for finding the quickest and cheapest way to send data across a network.
  • Routes: Three types of routing tables are used to keep track of routes. There are three types of routing: dynamic routing, static routing, and default routing. The selection of a path that leads to the destination and has certain characteristics along the way is what we mean when we talk about a route.

How does the process of routing work?

When a data packet is received by a network, the router immediately begins to read the headers, which include information regarding the packet’s ultimate destination. After that, it compares the information with the entries in the routing table (which is a list of objectives) and chooses which route is the most efficient to take to go to the desired location. In the end, the router will propose a route for the packets to take, which will involve passing through several other routers on the way to the destination node. Static routing, dynamic routing, and default routing are the three distinct categories of routing operations.

Why should we include Static Routes?

  • Because security concerns prevent some routes from being added to the default gateway device, you will need to make use of an additional routing device to carry out certain operations. In such a scenario, it is possible to configure a nearby Windows machine so that it can carry out the necessary routing functions.
  • On your network, you have created many subnets or VLANs, and now you need to route traffic to one of those subnets in particular. Testing these kinds of setups can be made significantly easier with the utilization of static routes.

What PowerShell cmdlet can be used to add a static route?

The Ip-route command is in charge of managing static routes in the routing table, and its responsibilities include these. Each static route that you want to add to the routing database requires that you issue this command on its own before you can do so. If you want to remove a static route, you can do so by using the no Ip-route command. Run this command for each static route that you want to take out of the routing database, and then exit the terminal.

The Step-by-Step Guide to Adding a Static Route Using PowerShell CMDLETs

Route if the condition is met, then the mask metric will be /f /p.

  1. The routing table can be cleared by using the command /f, which stands for “forward”.
  2. If you use the /p switch, the routing table will be added to the network in an irreversible way.
  3. The command is a notation that is used to specify the command that you wish to use, such as add, change, or delete. Examples of this kind of command include add, change, and delete.
  4. Insert /p after the route 192.168.0.0 mask 255.255.0.0 192.168.0.1 if 0x2

What steps must be taken to add a Static Route to the Windows Routing Table?

  • route [/f] [/p] [<command> [<destination>] [mask <netmask>] [<gateway>] [metric <metric>]] if the word “interface,” then the word “if”.
  • The -f switch removes from the routing table all entries that do not host routes (routes with a netmask of 255.255.255.255), in addition to the loopback network route.

When you run the add command with the -p switch in combination with it, the route that you specify will be added to the register. After that, this route will be utilized each time the TCP/IP protocol is launched to initialize the IP routing table.

  • Command: Identifies the command that will be carried out. The following are examples of valid commands: (add, change, delete, and print)
  • Destination: Indicates the area of the network where the route will eventually arrive at its final destination.
  • Mask: The netmask parameter provides information on the network destination’s netmask, which is also referred to as the subnet mask.
  • Gateway: Identifies the IP address of the next hop, which is also known as the forwarding IP address. This address is used to gain access to the set of addresses that are determined by the network destination and the subnet mask.
  • Metric: Specifies an integer cost metric for the route, which can range anywhere from one to nine thousand nine hundred ninety-nine. This value can be used to calculate the total cost of the route. This measure is utilized to select, from among the several routes contained in the routing table, the one that provides the best possible approximation to the final destination address of a packet that is being relayed. The option that will bring the greatest reduction in metric value is the one that will be chosen.
  • Interface: Indicates the index of the interface through which the destination can be reached. Destination: Indicates the name of the destination.
  • To find the PowerShell application, open the Windows search bar and type “powershell”. This will take you to the appropriate location.
  • While holding down the right mouse button, select the application you want to run, and then select the option to “Run as administrator”.
  • When the PowerShell command prompt appears, you should now type the following command to add the static route at this point.

route add 10.51.0.0 mask 255.255.0.0 10.23.0.1

Route with a static configuration and persistence

This route will only persist in the routing table until Windows is restarted, as was described before in this discussion. It is advised to use static routes that have persistence.

When this occurs, the information that was previously contained in the routing table will be removed completely. The command that was just explained needs to have the -p switch added to it for you to be able to make the entry permanent.

route with the address 10.51.0.0 inserted, masked with the address 255.255.0.0, and metric set to 65

The path that has been permanently established with an interface.

When using the route print command to view the routing table, the interface list numbers are displayed momentarily before the IPv4 route table. The index number 1 (0x1) is used to represent the loopback, while the remaining indices are dispersed throughout the many network interfaces that are currently in use.

route add 10.51.0.0 mask 255.255.0.0 10.23.0.1 if 0x7

Final Words

This post walked through the process of using PowerShell to add a static route to a routing table, along with a few other crucial factors, and showed how to do it. If you want to evaluate the information that you’ve included in the static route entries that you’ve established, using the route print command to view the routing table allows you to see all of your static route entries. This is beneficial if you wish to do so.

We hope that by the time you conclude this post, you will not only have a better grasp of the concept of a static route but also of how to design one in operating systems that use the Windows platform.

:/>  Автозагрузка в Windows 10: где находится и как с ней работать, настройка автозапуска программ различными способами

Оставьте комментарий