Как настроить статические ip-адреса dhcp в power shell

Leverage NinjaOne to view IP configurations and troubleshoot connectivity issues remotely.

Start your free trial!

In this tutorial, you will learn how to use a few network management cmdlets in PowerShell to help manage a Windows host’s IP address, gateway, and DNS settings.

Read on, and level up your network troubleshooting skills with PowerShell IP configuration commands!

В статье – Установка маршрутизатора pfSense в Hyper-V мы настроили маршрутизатор pfSense для работы в частной сети. Сегодня мы настроим Windows Server для работы в этой сети используя только командную строку PowerShell.

Запустим PowerShell из-под администратора.

Ah, Monday morning dramas — the boss has that “we’ve got a problem” look plastered on their face. Surprise, surprise! You’re moving offices, and guess who’s got to wave their IT magic wand to make your network play nice with the existing setup? Oh yes, it’s you! But hold on — before you start thinking of visiting each computer individually like it’s 1999, let’s introduce you to PowerShell. I present a PowerShell method for configuring static and DHCP IP addresses that utilizes the newer PowerShell cmdlets.

Newer versions of PowerShell mean more cmdlets

Microsoft implemented more PowerShell cmdlets, including some cmdlets that are specific to configuring network adapters and TCP/IP settings.

Using these commands, we can set various network configurations and settings more easily from a PowerShell script.

If you have multiple network adapters, you need to identify which network adapter you wish to view or modify by name, interface index, status, etc. For systems with one adapter, you can typically get this by using only Get-NetAdapter with no extra parameters. Please adjust this to suit your environment.

This cmdlet gets you the network configuration (interfaces, IP addresses, and DNS servers).

The Get-NetIPInterface cmdlet gets you the IP interfaces, which can include both IPv4 and IPv6 addresses and their associated configurations. We will use just IPv4 today, so my example reflects that.

The Set-NetIPInterface allows you to modify settings.

This cmdlet lets you set the DNS servers associated with a particular network interface.

This cmdlet lets you modify IP routes in the routing table, including wiping out all routes.

This cmdlet allows you to create and configure an IP address. This can include both IPv4 and IPv6 addresses.

How to set static/DHCP IP addresses

Enough of the boring explanations. Let’s move on to the fun!

We’re going to give a couple of examples for setting static and DHCP IP addresses by using the commands mentioned above.

Set a static IP address

In PowerShell, you can manage network adapter settings to disable or enable static (manually assigned) and DHCP (automatically assigned) IP addresses using the Set-NetIPInterface cmdlet. The specific command depends on whether you want to disable static or DHCP addresses. Here are the PowerShell commands for each scenario:

Disable a static IP address

To disable a static IP address on a network adapter, you can set the interface to obtain an IP address automatically (DHCP). Here’s the PowerShell command:

Replace “YourNetworkAdapterName” with the actual name or alias of your network adapter. This command configures the interface to obtain an IP address automatically from a DHCP server.

Disable DHCP (obtain IP automatically) and enable a static IP address

Replace “YourNetworkAdapterName” with the actual name or alias of your network adapter, “YourStaticIPAddress” with the desired static IP address you want to assign, “YourSubnetPrefixLength” with the subnet prefix length (e.g., 24 for a typical subnet mask of 255.255.255.0), and “YourDefaultGatewayIP” with the IP address of your default gateway.

Final thoughts

This is still just scratching the surface of what’s available. Remember to check out what properties and methods are available for Win32_NetworkAdapterConfiguration, and you’ll be able to customize all the settings for your particular environment. For a more complete list of cmdlets you can use to set network and TCP/IP settings, check out our PowerShell Commands Library.

Как настроить статические ip-адреса dhcp в power shell

Jordan had spent his life wondering why tasks he didn’t like to do had no options to complete themselves. Eventually he had to make that happen on his own. It turned out that he enjoyed making tasks complete themselves, and PDQ thought that is something he should talk about on the internet.

PowerShell is a powerful CLI Windows management tool. It has tons of commands that are used for network management. One such command is ipconfig.

What is Ipconfig (Internet Protocol Configuration)

PowerShell Ipconfig Commands

What is Ipconfig (Internet Protocol Configuration)?

The Ipconfig is the acronym of the Internet Protocol Configuration. It displays the list of network adapters, gateways, IPv4, and IPv6 protocol configurations when executed without parameters. Its core purpose is to manage the DHCP, DNS, and IP addresses. It has several parameters and each parameter has its significance in terms of retrieving internet protocol configuration.

PowerShell Ipconfig Commands

There is no such hard rule to use the ipconfig commands. There is a simple way to use it and that is to type and execute them in PowerShell. However, information can be learned as to when and how to use them. Thus, the list of ipconfig commands along with their practical usage and information is provided below.

:/>  Что делать если тупит ноут

Ipconfig /all

The ipconfig /all command gets all IP configurations. It lists all the network adapters including wireless networks and wired LAN networks. It displays the configuration of each adapter connected. Network configuration includes the details of media state, physical address, or DHCP status.

Example

The ipconfig /all command gets the configuration of the TCP/IP adapters:

Как настроить статические ip-адреса dhcp в power shell

Ipconfig /displaydns

The ipconfig /displaydns command gets DNS resolver caches content. It displays all the cached DNS records with complete details, including record name, type, TTL, data length, section, and CNAME record.

To get the cached DNS details, execute the given command in the PowerShell console:

Как настроить статические ip-адреса dhcp в power shell

Ipconfig /flushdns

The ipconfig /flushdns command purges the DNS resolver cache. It clears the locally cached DNS records. Even though Windows does clear the cached DNS records automatically. But, it can be cleared manually with a single ipconfig /flushdns command.

To clear the cached DNS records manually, type and run this command:

Как настроить статические ip-адреса dhcp в power shell

Ipconfig /registerdns

The ipconfig /registerdns command creates or registers a DNS server. It does so by using the hostname and IP address of the computer on which the command is being executed. It informs the DNS server to register or update the DNS records for the current computer.

To update or register the DNS server of the computer, overview this command:

Как настроить статические ip-адреса dhcp в power shell

Ipconfig /release

The ipconfig /release command releases the currently assigned IP address to a computer.

To release the IP address assigned to a computer, execute this command:

Как настроить статические ip-адреса dhcp в power shell

Note: To release currently assigned IPv6 configurations for the DHCP server, use this command:

Как настроить статические ip-адреса dhcp в power shell

Ipconfig /renew

The ipconfig /renew command renews the IPv4 address on the DHCP adapters. It renews the IP address for all adapters when any of the adapters is not specified to it. This command is usually executed after the use of the ipconfig /release cmdlet.

To renew the computer’s IP address on the DHCP adapters, use this command:

Как настроить статические ip-адреса dhcp в power shell

Note: To renew the IP address for version 6 adapters, overview the below command:

Как настроить статические ip-адреса dhcp в power shell

Ipconfig /showclassid

The ipconfig /showclassid command gets the DHCP class ID for an adapter.

To get the DHCP class ID for all the adapters, use this command:

Как настроить статические ip-адреса dhcp в power shell

Ipconfig /setclassid

The Ipconfig /setclassid command configures the DHCP class ID for the specified adapter. If the asterisk (*) is specified to the Ipconfig /setclassid command then it configures the class ID for all the available adapters.

This command will set the DHCP class ID for all the adapters:

Как настроить статические ip-адреса dhcp в power shell

The ipconfig /? command displays all the available ipconfig commands and instructions to use them.

To get the list of ipconfig commands and helping material, use this command:

Как настроить статические ip-адреса dhcp в power shell

Ipconfig /allcompartments

The ipconfig /allcompartments displays the information regarding all compartments. It retrieves the same information as the ipconfig command does without parameters.

To get all the ipconfig compartments and their information, execute this command:

Как настроить статические ip-адреса dhcp в power shell

Summary

The ipconfig command outputs TCP/IP network configurations. It lists down network adapters, gateways, IPv4, and IPv6 protocol configurations. It manages the DHCP, DNS, and IP addresses. It has several other commands such as all, release, renew, flushdns, registerdns, and displaydns. Each command has its use when it comes to managing the IP configurations.

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.

Установка статического адреса

Выполним в консоли:

Set-DnsClientServerAddress -InterfaceIndex 12 -ServerAddresses (172.16.0.254)

Проверим настройки сети:

Настройка протокола IP для Windows
  Имя компьютера  . . . . . . . . . : sd-server-1
  Основной DNS-суффикс  . . . . . . : soft.altuninvv.ru
  Тип узла. . . . . . . . . . . . . : Гибридный
  IP-маршрутизация включена . . . . : Нет
  WINS-прокси включен . . . . . . . : Нет
  Порядок просмотра суффиксов DNS . : soft.altuninvv.ru
Ethernet adapter Ethernet:
  DNS-суффикс подключения . . . . . :
  Описание. . . . . . . . . . . . . : Сетевой адаптер Hyper-V (Майкрософт)
  Физический адрес. . . . . . . . . : 00-15-5D-01-28-02
  DHCP включен. . . . . . . . . . . : Нет
  Автонастройка включена. . . . . . : Да
  IPv4-адрес. . . . . . . . . . . . : 172.16.0.1(Основной)
  Маска подсети . . . . . . . . . . : 255.255.255.0
  Основной шлюз. . . . . . . . . : 172.16.0.254
  NetBios через TCP/IP. . . . . . . . : Включен

Проверим доступность шлюза:

Обмен пакетами с 172.16.0.254 по с 32 байтами данных:
Ответ от 172.16.0.254: число байт=32 время<1мс TTL=64
Ответ от 172.16.0.254: число байт=32 время<1мс TTL=64
Ответ от 172.16.0.254: число байт=32 время<1мс TTL=64
Ответ от 172.16.0.254: число байт=32 время<1мс TTL=64

Шлюз доступен и сайты открываются.

Getting the IP Route Information (Get-NetRoute)

An IP address enables a host to communicate with others on the same network. But what happens when the host needs to communicate outside that network?

A gateway address is necessary, and the Get-NetRoute cmdlet is what you need. This cmdlet provides information that previous cmdlets you have learned about do not.

Run the below Get-NetRoute command to check the current gateway (NextHop) for the Ethernet interface.

Typically, a DHCP server supplies the gateway address. You’ll want to capture this address later for this article.

:/>  Что такое прокси-серверы и как ими пользоваться

Как настроить статические ip-адреса dhcp в power shell

Finding the gateway address assigned to an interface

Commonly used ipconfig commands

Let’s explore what ipconfig can do, go over some of the common parameters used with ipconfig commands, and review some of the information you can access with these commands.

What does just ipconfig do?

Your screen will display information about all of your network adaptors, including ethernet, wireless, and VPN if you’re using one.

What does the ipconfig /all command do?

ipconfig /all and press enter.

This command returns a detailed list of network adapters and their respective configurations, including:

Examining the output of the ipconfig /all command tells you if there are any misconfigurations or potential issues that may be affecting your network connectivity.

Using ipconfig commands to release and renew your IP address

Executing the ipconfig /release command releases the IP address and makes it available for reassignment. This is useful when you need to obtain a new IP address due to issues like network conflicts.

To request a new IP address for a specific network interface, go to Command Prompt and type:

This command makes your computer send a DHCP (Dynamic Host Configuration Protocol) request to the network’s DHCP server, asking for a new IP address assignment.

Using these ipconfig commands in conjunction with each other can often resolve connectivity issues and ensure that your network interface is configured properly.

What does the ipconfig displaydns command do?

ipconfig displaydns and press enter.

The DNS resolver cache stores information about previously resolved DNS queries, such as the IP address of visited websites. The ipconfig displaydns command provides you with a list of all the DNS records stored in the cache. This is useful for troubleshooting DNS-related issues and allows you to check if the DNS resolver cache is holding outdated or incorrect information.

What is the impact of ipconfig registerdns?

To manually refresh and update the DNS resolver cache on your computer, go to Command Prompt and type:

This command directs your computer to send a registration request to the DNS server, updating the DNS records associated with your computer. The ipconfig registerdns command comes in handy when you need to troubleshoot DNS-related issues or when you want to ensure that your computer’s DNS records are up to date. Executing ipconfig registerdns lets you resolve DNS conflicts, update outdated records, and improve the overall efficiency of your DNS resolution process.

NinjaOne simplifies IT troubleshooting by using familiar command-line arguments for in-depth configuration, like an enhanced ipconfig.

Configuring IP, Gateway, and DNS Address Manually

With the cmdlets you have learned so far, it is time to put your new knowledge to work. For this tutorial, you will assign a static IP address, gateway, and DNS servers to a Windows Server 2022 host.

The commands from this point forward only change the IP address, gateway, and DNS settings for the specified network adapter. You must repeat these steps for each adapter you want to change.

Find installed network adapters command

Identify the network adapter that you want to change. You can use the adapter’s name or the index number displayed in the list (i.e., Ethernet).

Как настроить статические ip-адреса dhcp в power shell

Current network adapter properties of all installed adapters

Как настроить статические ip-адреса dhcp в power shell

Setting a new IP address and gateway

Related to the New-NetIPAddress cmdlet is Set-NetIPAddress, which changes existing IP configuration, while Remove-NetIPAddress expunges a configuration.

Note that with the Set-DnsClientServerAddress cmdlet, you can assign one or more internal or public-facing DNS IP addresses.

4. Lastly, run the below Restart-NetAdapter command, which does not print output to the console but restarts your network adapter and applies the changes. Congratulations! You have just manually configured your network interface with a custom configuration.

Restart-NetAdapter -Name Ethernet

If your host only has one adapter, like in this tutorial, you may lose connectivity briefly, depending on how you are connected. This last step is essential to complete to start using the new IP address.

Getting IP Network Configurations (Get-NetIPConfiguration)

When you need the information the previous three cmdlets you have learned about in one go, the Get-NetIPConfiguration cmdlet will do the trick. This cmdlet’s one prominent feature is it provides more focused information.

Run the Get-NetIPConfiguration cmdlet below to display the IP network configurations gathered by the previous cmdlets you ran.

Как настроить статические ip-адреса dhcp в power shell

Getting IP network configurations

The Get-NetIPConfiguration cmdlet is quicker if you only have one network interface. But if you have more than one network interface, you may have to filter out properties to prevent the console from scrolling.

Отключаем IPv6 через командную строку

Get-NetAdapterBinding -ComponentID ‘ms_tcpip6’

Name                           DisplayName                                        ComponentID          Enabled
—-                           ———–                                        ———–          ——-
Ethernet                       Протокол Интернета версии 6 (TCP/IPv6)             ms_tcpip6            True

Проверим еще раз:

Name                           DisplayName                                        ComponentID          Enabled
—-                           ———–                                        ———–          ——-
Ethernet                       Протокол Интернета версии 6 (TCP/IPv6)             ms_tcpip6            False

IPv6 отключен на сервере.

Gain insight with ipconfig

IPConfig commands are widely used, for good reason: They give you insight so you can manage and troubleshoot network connectivity issues. When combined with a wide range of command line arguments, ipconfig commands provide valuable information about your network configuration.

:/>  Как включить консоль

These commands also allow you to customize and fine-tune your settings, diagnose network problems, release and renew IP addresses, view DNS cache contents, and update DNS records, among other operations.

Along with ipconfig commands, other command-line arguments can also save time and automate processes. Having all of these tools in your toolbox can give you an edge in managing your network.

To further maximize your computing resources, take a look at NinjaOne’s endpoint management software. It supports command-line arguments and provides features such as monitoring and alerting, software deployment, and patch management. Sign up for a

Отключаем DHCP-клиент на интерфейсе через командную строку

ComputerName                : SD-SERVER-1
InterfaceAlias              : Ethernet
InterfaceIndex              : 12
InterfaceDescription        : Сетевой адаптер Hyper-V (Майкрософт)
NetAdapter.LinkLayerAddress : 00-15-5D-01-28-02
NetAdapter.Status           : Up
NetProfile.Name             : soft.altuninvv.ru
NetProfile.NetworkCategory  : DomainAuthenticated
NetProfile.IPv6Connectivity : NoTraffic
NetProfile.IPv4Connectivity : LocalNetwork
IPv4Address                 : 192.168.1.39
IPv4DefaultGateway          : 192.168.1.1
NetIPv4Interface.NlMTU      : 1500
NetIPv4Interface.DHCP       : Enabled
DNSServer                   : 127.0.0.1

Указывает что DHCP-клиент включен на интерфейсе.

Отключим DHCP, для этого нам нужен индекс интерфейса:

Set-NetIPInterface -ifIndex 12  -Dhcp Disabled

Retrieving an Address PowerShell IP Configuration (Get-NetIPAddress)

You previously listed all the network interfaces with a single command. But you can also list property values and your host’s current IP address via the Get-NetIPAddress cmdlet.

Run the below cmdlet (without parameters) to display each adapter’s address and PowerShell IP configuration.

Как настроить статические ip-адреса dhcp в power shell

Getting all IP address configurations

Как настроить статические ip-адреса dhcp в power shell

Finding the IP address assigned to an interface (Ethernet)

Getting DNS Server IP Addresses (Get-DnsClientServerAddress)

DNS is necessary for name resolution for both internal and external networks. Without DNS, you would have to remember the internet address for each host on your network.

But chances are that your host has DNS already configured through DHCP. You can use the Get-DnsClientServerAddress cmdlet to verify the current configuration.

Record the IP addresses by redirecting the output to a text file or writing them down. You will need to reassign these DNS server addresses later in this tutorial.

Как настроить статические ip-адреса dhcp в power shell

Verifying the current DNS configuration

Advantages of ipconfig and command line arguments

The ipconfig command displays the full system configuration, speeding up troubleshooting. This makes it easy to spot connectivity problems or IP address conflicts and correct them.

Furthermore, ipconfig commands offer a wide range of command line arguments that allow you to customize and fine-tune your network configuration. Understanding command line arguments helps you effectively manage your network configuration and resolve connectivity problems with ease.

Удаляем все ip-адреса через командную строку

Очистим все уже установленные адреса, если они есть:

Remove-NetIPAddress -InterfaceIndex 12 -AsJob

Set-DnsClientServerAddress -InterfaceIndex 12 -ServerAddresses (127.0.0.1)

Настройки сети сброшены!

Getting Network Adapter Properties (Get-NetAdapter)

In troubleshooting or gathering a host’s IP address, you could use traditional tools like ping, ipconfig, or sconfig. But with PowerShell cmdlets, you can script this process for automation.

Open PowerShell and run the below Get-NetAdapter cmdlet to get the list of network adapters and their properties, such as your host’s InterfaceAlias and InterfaceIndex.

Как настроить статические ip-адреса dhcp в power shell

Getting network adapters’ properties

Note that your adapter does not have an IP Address object yet. You need to know which one you are going to use. For this tutorial, you are working with the adapter alias of Ethernet.

What is ipconfig command used for?

The ipconfig command, short for Internet Protocol Configuration, is a command-line utility that provides detailed information about your computer’s network settings. By entering specific ipconfig commands, you can retrieve useful data such as:

You can also perform several actions that allow you to resolve certain network issues such as conflicts or misconfigurations.

Available on all Windows operating systems, the ipconfig command is particularly useful for troubleshooting network connectivity issues, configuring network settings, and obtaining information about network interfaces. Whether you’re connected to a local area network (LAN), the internet, or a virtual private network (VPN), ipconfig commands can provide you insight into your network configuration.

Conclusion

Knowing your network configuration is crucial to keeping a healthy network. The good news is that you learned about four basic network configuration commands available from PowerShell IP configuration cmdlets.

With this newfound knowledge, you can easily create a script using PowerShell IP configuration abilities as part of a broader server configuration process.

What comes next? Why not try adjusting more advanced options like MTU, adding more routes, or resetting an adapter to use DHCP instead of a static address?

Заключение

Сегодня мы рассмотрели настройку локальной сети в Windows Server с использованием PowerSell:

Отключили получения адреса посредством DHCP;

Удалили все адреса с интерфейса;

Удалили все маршруты;

Установили адрес DNS для интерфейса как 127.0.0.1;

Отключили IPv6 на интерфейсе:

Установили статический адрес, шлюз и адрес DNS-сервера для интерфейса.

Проверили настройки и доступность сети Интернет.

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