Настройка dhcp windows server 2019 powershell

Данная статья описывает процедуру установки и настройки DHCP сервера на базе Windows Server 2019. В статье описаны особенности установки и настройки DHCP роли, создания областей DHCP, настройки их параметров и резервации статических адресов. Мы рассмотрим как привычный способ настройки параметров DHCP сервера через графическую консоль, так и настройку DHCP из командной строки PowerShell.

Протокол DHCP (Dynamic Host Configuration Protocol) используется для автоматического назначения сетевых настроек (IP адрес, маска подсети, шлюз, DNS сервера и т.д.) устройствам в вашей сети (компьютеры, ноутбуки, сканеры, принтеры и т.д.). Также DHCP сервер позволяет более эффективно использовать адресное пространство, избегать конфликта IP адресов в сети и централизованно управлять сетевыми параметрами на клиентских устройствах.

Содержание:

  • Установка роли DHCP сервера в Windows Server 2019/2016
  • Настройка DHCP областей в Windows Server
  • Резервация IP адресов на DHCP сервере
  • Настройка и управление DHCP сервером с помощью PowerShell

Установка роли DHCP сервера в Windows Server 2019/2016

В этом примере мы установим DHCP сервер на хосте с Windows Server 2019 и IP адресом 192.168.13.4. Вы можете использовать как Server Core версию, так и Full GUI. В маленькой инфраструктуре допустимо устанавливать DHCP сервер на сервер с ролью контроллера домена Active Directory.

Обязательно назначьте статический IP адрес серверу с ролью DHCP сервер. При установке роли DHCP из консоли PowerShell на сервере с автоматическим получением IP адреса появляется предупреждение:

Configure at least one static IP address on your computer before installing DHCP.
WARNING: The following recommended condition is not met for DHCP: No static IP addresses were found on this computer. If the IP address changes, clients might not be able to contact this server. Please configure a static IP address before installing DHCP Server.

Установить роль DHCP Server можно из консоли Server Manager (Add Roles and Features -> Server Roles).

установка роли DHCP server в windows server 2019

После установки роли DHCP роли нужно выполнить Post-Deployment Configuration. Для этого в консоли Server Manager щелкните по уведомлению и выберите Complete DHCP configuration.

выберите Complete DHCP configuration

Вам будет предложено аутентифицировать новый DHCP сервер в Active Directory (экран Authorization). Для авторизации DHCP сервера в AD учетная запись должна состоять в доменной группе Enterprise Admins.

Если у вас нет прав на авторизацию DHCP в AD, вы можете указать, чтобы ваш DHCP сервер запускался без проверки авторизации в домене:

Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DHCPServer\Parameters" -Name DisableRogueDetection -Value 1 -Force

авторизовать сервер DHCP в Active Directory

Также вы можете установить и настроить DHCP роль в Windows Server из консоли PowerShell.

Установка роли DHCP:

Install-WindowsFeature DHCP –IncludeManagementTools

Проверьте, что роль и инструменты управления RSAT-DHCP установлены:

Get-WindowsFeature -Name *DHCP*| Where Installed

установка DHCP сервера с помощью powershell

Авторизуйте DHCP сервер в Active Directory (укажите DNS имя сервера и IP адрес, который будет использоваться DHCP клиентами):

Add-DhcpServerInDC -DnsName hq-dc01.contoso.com -IPAddress 192.168.13.4

Создайте локальные группы безопасности DHCP сервера:

Add-DhcpServerSecurityGroup

Чтобы Server Manager перестал показывать уведомление о том, что DHCP роль требует настройки, выполните команду:

Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\ServerManager\Roles\12 -Name ConfigurationState -Value 2

Перезапустите службу DHCPServer:

Restart-Service -Name DHCPServer -Force

База данных и логи DHCP сервера находятся в каталоге
%systemroot%\system32\dhcp
.

  • dhcp.mdb — файл базы данных сервера DHCP’;
  • j50.log – транзакционный журнал (используется при восстановлении конфигурации DHCP);
  • j50.chk — файл контрольной точки;
  • tmp.edb — временный рабочий файл DHCP-сервера.

Настройка DHCP областей в Windows Server

После установки роли DHCP вам нужно создать DHCP области (Scopes), которые описывают диапазоны IP адресов и другие настройки, выдающиеся сервером клиентам.

Для управления сервером DHCP используется консоль dhcpmgmt.msc (вы можете управлять DHCP сервером локально или с удаленного компьютера с установленным RSAT). Запустите консоль DHCP, разверните ваш сервер -> IPv4.

Чтобы создать новую область выберите New Scope.

создать новую dhcp область

Укажите название DHCP области.

название DHCP области

Укажите диапазон IP адресов, который будет выдаваться этой областью и маску сети. В этом примере я хочу использовать эту DHCP область для обслуживания подсети 192.168.100.0/24. В рамках этой сети DHCP сервером будет назначаться динамические IP адреса из диапазона 192.168.100.50 — 192.168.100.250. В следующем окне можно добавить исключения в этот диапазон (Add Exclusions and Delay).

диапазон IP адресов области DHCP

Далее нужно указать длительность аренды (Lease Duration) IP адреса DHCP клиентом (по умолчанию 8 дней, менять без особой необходимости не нужно).

срока аренды адреса на dhcp

Укажите, что вы хотите настроить дополнительный параметры DHCP области.

настроить опции dhcp области .

Укажите IP адрес шлюза в подсети, который должен назначаться клиентам (в нашем примере это 192.168.100.1).

задать адрес шлюза по-умолчанию для dhcp области

Затем укажите имя домена и адреса DNS серверов, которые будут назначены клиентам DHCP.

настройки DNS для DHCP области

Осталось активировать DHCP область (разрешить ей обслуживать клиентов).

активировать DHCP зону

DHCP сервер может выдавать клиентам различный настройки (кроме IP адреса). Для этого используются Scope Options.

В Windows Server DHCP можно настроить глобальные настройки области или Scope Options для каждой области.

опции DHCP scope

Ранее мы уже настроили три опции области:

  • 003 Router
  • 006 DNS Server
  • 015 DNS Domain Name

Можно добавить и другие опции (NTP сервера, PXE и т.д.).

В разделе Server Options DHCP сервера можно настроить глобальные опции, которые будут наследуются всеми областями. Но вы можете переопределить глобальные настройки в настройках каждой области (опции области имеют приоритет над опциями сервера).

настроить параметры DHCP сервера

Один DHCP сервер может обслуживать сотни удаленных подсетей и VLAN. Поэтому вы можете создать на нем несколько областей. Главное, чтобы в каждой из подсетей был настроен ретранслятор (DHCP relay agent), который пересылает широковещательные DHCP-запросы на указанный DHCP сервер. В терминах Cisco DHCP ретранслятор называется ip helper. Вы можете настроить DHCP Relay даже на Windows Server.

Протокол DHCP в качестве транспорта использует протокол UDP. Пакеты от клиента к серверу передаются по порту 67 UDP, обратно через UDP 68

Резервация IP адресов на DHCP сервере

По умолчанию DCHP сервер выдает клиентам динамические адреса. Это означает что IP адрес у любого клиента может меняться. Если вы хотите, чтобы определенные устройства всегда получали от DHCP сервера один и тот же адрес, вы можете его зарезервировать (например, для сетевых принтеров, которые настроены у пользователей).

Для DHCP резервации выберите область и перейдите в секции Reservation. В меню выберите New Reservation.

Резервация IP адреса на DHCP

При создании резервации нужно указать IP адрес, который нужно сохранить за клиентом и его MAC адрес (уникальное значение). MAC адрес в Windows можно получить из результатов команды
ipconfig /all
или с помощью PowerShell
get-netadapter|select name,macaddress
). Опционально можно указать имя и описание устройства.

Укажите MAC адрес устройства для резервации IP адреса на DHCP

Также вы можете зарезервировать текущий динамический адрес за устройством, найдя его в разделе Address Leases. Щелкните по устройству и выберите Add to Reservation.

Add to Reservation

Настройка и управление DHCP сервером с помощью PowerShell

Все операции по настройке и управлению DHCP сервером на Windows Server 2019/2016 можно выполнять из консоли PowerShell. Рассмотрим основные команды управления DHCP. Для этого используется модуль DHCPServer. Импортируйте модуль в сессию:

Import-Module DHCPServer

Вывести полный список командлетов в моделе DHCP можно так:

Get-Command -Module DHCPServer

PowerShell модуль DHCPServer

Следующая команда выведет список авторизованных DHCP серверов в Active Directory:

Get-DhcpServerInDC

Вывысти список DHCP серееров в домене

Вывести список DHCP областей на указанном сервере:

Get-DhcpServerv4Scope –ComputerName msk-dhcp1

Если нужно показать все параметры области (Delay, Description, Name и т.д.):

Get-DhcpServerv4Scope –ComputerName msk-dhcp1| FL *

Список областей на DHCP сервере

Если нужно отобразить данные о IPv6 областях:

Get-DHCPServerv6Scope

Получить настройки для конкретной области:

Get-DhcpServerv4Scope –ComputerName msk-dhcp1 –ScopeID 10.10.1.0

Создадим новую (неактивную) область с диапазоном адресов с 192.168.113.50 до 192.168.113.250:

Add-DhcpServerv4Scope -Name “Brahch1 192.168.113.0” -StartRange 192.168.113.50 -EndRange 192.168.113.250 -SubnetMask 255.255.255.0 -State InActive

Настроить следующие параметры DHCP сервера: DNS сервер, домен и адрес шлюза по-умолчанию:

Set-DhcpServerv4OptionValue -ScopeID 192.168.113.0 -DnsDomain contoso.com -DnsServer 192.168.13.4 -Router 192.168.113.1

Добавить исключения в DHCP область:

Add-DhcpServerv4ExclusionRange -ScopeID 192.168.113.0 -StartRange 192.168.113.90 -EndRange 192.168.113.100

Активировать DHCP область:

Set-DhcpServerv4Scope -ScopeID 192.168.113.0 -State Active

Add-DhcpServerv4Scope - создать и настроить области на DHCP сервере командами PowerShell

Для удобства можно использовать такую команду PowerShell при создании новой области:

$HashArgs = @{
'Name' = 'EKB Office Scope';
'Description' = 'workstations';
'StartRange' = '192.168.140.10';
'EndRange' = '192.168.140.200';
'SubnetMask' = '255.255.255.0';
'State' = 'Active';
'LeaseDuration' = '1.00:00:00';
}
Add-DhcpServerv4Scope @HashArgs

Опции для DHCP сервера добавляется так (к примеру, WPAD):

Add-DhcpServerv4OptionDefinition -ComputerName msk-dhcp1 -Name WPAD -OptionId 252 -Type String

Вывести список настроенных опций DHCP сервера можно так:

Get-DHCPServerv4OptionValue -ComputerName msk-dhcp1 | Format-List

Выведем список настроенных параметров зоны:

Get-DHCPServerv4OptionValue -ComputerName msk-dhcp1 -ScopeId 10.10.1.0 | Format-List

Показать текущий список арендованных адресов для области 10.10.1.0:

Get-DHCPServerv4Lease -ScopeId 10.10.1.0 -ComputerName msk-dhcp1

Список аренд на DHCP сервере

Создать DHCP резервацию для клиента, которому назначен динамический IP адрес 10.10.1.88 (конвертировать выданный адрес в зарезервированный):

Get-DhcpServerv4Lease -ComputerName msk-dhcp1 -IPAddress 10.10.1.88| Add-DhcpServerv4Reservation -ComputerName msk-dhcp1

Можно массово зарезервировать IP адреса для компьютеров по списку из csv файла. Для этого создайте текстовый файл в формате:

ScopeId,IPAddress,Name,ClientId,Description
10.10.1.0,10.10.1.88,Client1,ba-ab-5c-3d-4e-6f,Reservation PC-msk-s1
10.10.1.0,10.10.1.89,Client2,ba-ab-5c-5d-2e-3f,Reservation PC-msk-s2

Сохраните файл с именем
c:\dhcp\DHCPReservations.csv
и запустите следующую команду, которая импортирует данные из csv файла и создаст DHCP резервации для клиентов:

Import-Csv –Path c:\dhcp\DHCPReservations.csv | Add-DhcpServerv4Reservation -ComputerName msk-dhcp1

Отключить область на DHCP сервере:

Set-DhcpServerv4Scope -ComputerName msk-dhcp1-ScopeId 10.10.1.0-State InActive

Удалить область с DHCP сервера:

Remove-DHCPServerv4Scope -ComputerName msk-dhcp1-ScopeId 10.10.1.0 -Force

Возможно получить статистику DHCP сервера (количество областей, резерваций, процент использования адресов и пр.).

Get-DhcpServerv4Statistics -ComputerName msk-dhcp1

Статистика использования DHCP сервера

Аналогичная информация для конкретной области может быть получена с помощью командлета Get-DhcpServerv4ScopeStatistics.

Конфигурацию DHCP сервера можно экспортировать в указанный XML файл с помощью команды:

Export-DHCPServer -ComputerName msk-dhcp1 -File C:\dhcp\dhcp-export.xml

Совет. Заданием с такой командой в планировщике задач можно реализовать регулярное резервное копирование конфигурации DHCP сервера.

В дальнейшем эти настройки DHCP сервера можно импортировать (перенести) на другой DHCP сервер:

Import-DHCPServer -ComputerName msk-dhcp2 -File C:\dhcp\dhcp-export.xml -BackupPath C:\dhcpbackup\

RIn this guide, we’ll walk you through how to install and configure a DHCP server based on Windows Server 2019. We’ll cover both the usual way to configure DHCP server options through a GUI console and DHCP configuration from the PowerShell command line. This article describes the specifics of installing and configuring a DHCP role on Windows Server, creating DHCP scopes, configuring scope options, and reserving static IP addresses.

DHCP (Dynamic Host Configuration Protocol) is used to automatically assign network settings (IP address, subnet mask, gateway, DNS server, etc.) to devices on your network (computers, laptops, scanners, printers, etc.). Also, the DHCP server allows you to more efficiently use the IP address space, avoid the conflict of IP addresses in the network and centrally manage the network parameters on client devices.

Installing DHCP Server Role on Windows Server 2019/2016

In this example, we will install a DHCP server on a Windows Server 2019 host with an IP address 192.168.13.4. You can use both Windows Server Core and Full GUI versions. In a small infrastructure, it is acceptable to install a DHCP server on a server with the role of an Active Directory domain controller.

Be sure to assign a static IP address to the DHCP server host. When installing the DHCP role from the PowerShell console on a server with a dynamic IP address, a warning appears:

Configure at least one static IP address on your computer before installing DHCP.
WARNING: The following recommended condition is not met for DHCP: No static IP addresses were found on this computer. If the IP address changes, clients might not be able to contact this server. Please configure a static IP address before installing DHCP Server.

You can install the DHCP Server role from the Server Manager console (Add Roles and Features -> Server Roles).

install DHCP Server role on Windows Server 2019

After installing the DHCP role, you need to perform post-deployment configuration. To do this, in the Server Manager console, click on the notification and select Complete DHCP configuration.

Complete DHCP configuration Post-Deployment

You will be prompted to authorize the new DHCP server in Active Directory (Authorization screen). To authorize the DHCP server in AD, your account must be a member of the Enterprise Admins domain group.

If you don’t have permission to authorize DHCP in AD, you can specify that your DHCP server can start without checking for domain authorization:

Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\DHCPServer\Parameters" -Name DisableRogueDetection -Value 1 -Force

authorize this DHCP server in ADDS

You can also use the following commands in the PowerShell console to install and configure the DHCP server role on Windows Server:

Install-WindowsFeature DHCP –IncludeManagementTools

Verify that the DHCP role and RSAT-DHCP management tools are installed:

Get-WindowsFeature -Name *DHCP*| Where Installed

Install-WindowsFeature dhcp - install role using PowerShell

Authorize the DHCP server in Active Directory (specify the DNS name of the server and the IP address that will be used by DHCP clients):

Add-DhcpServerInDC -DnsName hq-dc01.woshub.com -IPAddress 192.168.13.4

Create local security groups for the DHCP server:

Add-DhcpServerSecurityGroup

To stop Server Manager from displaying a notification that the DHCP role requires additional configuration, run the command:

Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\ServerManager\Roles\12 -Name ConfigurationState -Value 2

Restart the DHCPServer service:

Restart-Service -Name DHCPServer -Force

The DHCP server database and logs are stored in %systemroot%\system32\dhcp:

  • dhcp.mdb — DHCP server database file;
  • j50.log – transaction log file (used when restoring DHCP configuration);
  • j50.chk — checkpoint file;
  • tmp.edb — DHCP server temporary working file.

Configuring DHCP Scopes on Windows Server 2019

After installing the DHCP role, you need to create DHCP scopes that describe the IP address ranges and other parameters that the server assigns to clients.

The dhcpmgmt.msc console is used to manage the DHCP server (you can manage the DHCP server locally or from a remote computer with RSAT installed). Open the DHCP console, expand your server, right-click IPv4, then select New Scope.

create new dhcp scope on windows server 2019

Set the name of the DHCP scope.

set dhcp scope name

Specify the range of IP addresses that will be issued by this DHCP scope and the subnet mask. In this example, I want to use this DHCP scope for the 192.168.100.0/24 network. Within this network, the DHCP server will assign dynamic IP addresses from the range 192.168.100.50 - 192.168.100.250. In the next window, you can add exclusions to this range (Add Exclusions and Delay).

configure dhcp scope IP address range and subnet mask

Next, you need to specify the lease duration of the DHCP client’s IP address (by default, it is 8 days, and you don’t need to change it without special need).

configure lease duration for dhcp scope

Select that you want to configure additional DHCP scope options.

configure additional dhcp scope options .

Specify the IP address of the default gateway in the network that should be assigned to clients (in our example, this is 192.168.100.1).

add router (default gateway) in DHCP scope

Then specify the domain name and DNS IP server addresses to be propagated to DHCP clients.

DNS settings for DHCP clients

It remains to activate the DHCP scope (allow it to serve clients).

activate dhcp scope

DHCP server can assign different settings to clients (except IP address). Scope Options are used for this.

In Windows Server DHCP, you can configure global scope settings or Scope Options for each scope.

configure dhcp scope options

We have previously configured three scope options:

  • 003 Router
  • 006 DNS Server
  • 015 DNS Domain Name

Other options can be added (NTP server, PXE settings, etc.).

In the Server Options section of the DHCP server, you can configure global options that will be inherited by all scopes. However, you can override the global settings in the settings of each scope (scope options take precedence over server options).

Server Options in DHCP console on Windows Server 2019

A single DHCP server can serve hundreds of subnets and VLANs. Thus, you can create multiple scopes on it. The main thing is that a DHCP relay agent must be configured on each of the subnets that forwards broadcast DHCP requests to your DHCP server. In Cisco terms, the DHCP relay is called ip helper. You can even configure DHCP Relay on the Windows Server host.

DHCP uses UDP protocol as a transport. Packets from the client to the server are transmitted over port 67 UDP, and back over UDP 68.

Configuring IP Address Reservation on a DHCP Server

By default, the DCHP server leases dynamic addresses to clients. This means that the IP address of any client can change. If you want certain devices to always receive the same static IP address from the DHCP server, you can reserve it (for example, for network printers connected to users’ computers).

To create a DHCP reservation, select a scope and go to the Reservation section. Select New Reservation from the menu.

windows server - create dhcp reservation

When creating a reservation, you need to specify the IP address you want to assign to the device and its unique MAC address. The MAC address in Windows can be obtained from the results of the ipconfig /all command or by using PowerShell (Get-NetAdapter | select Name, Macaddress). Optionally, you can specify the name and description of the device.

set dhcp reservation parameters and MAC address

You can also reserve the current dynamic address for a device by finding it in the Address Leases section of the DHCP console. Click on the device and select Add to Reservation.

reserve a leased IP address in dhcp

How to Configure and Manage DHCP Server with PowerShell?

You can perform all the operations for configuring and managing the DHCP server in Windows Server 2019/2016 from the PowerShell console. Let’s take a look at the basic DHCP management commands. The DHCPServer module is used for this. Import the module into the PowerShell session:

Import-Module DHCPServer

You can display a complete list of cmdlets in the DHCP module like this:

Get-Command -Module DHCPServer

list on command in DHCPServer PowerShell module

Let’s display the list of authorized DHCP servers in Active Directory:

Get-DhcpServerInDC

Display the list of authorized DHCP in AD

Get the list of DHCP scopes on the specified server:

Get-DhcpServerv4Scope –ComputerName be-dhcp1

If more scope displayed fields are required (Delay, Description, Name, etc.):

Get-DhcpServerv4Scope –ComputerName be-dhcp1| FL *

Get-DhcpServerv4Scope

If the information about IPv6 scopes has to be displayed:

Get-DHCPServerv6Scope

Get the settings of a certain DHCP scope:

Get-DhcpServerv4Scope –ComputerName be-dhcp1 –ScopeID 192.168.12.0

Let’s create a new inactive DHCP scope with the IP address range from 192.168.113.50 to 192.168.113.250:

Add-DhcpServerv4Scope -Name “NY Branch1 192.168.113.0” -StartRange 192.168.113.50 -EndRange 192.168.113.250 -SubnetMask 255.255.255.0 -State InActive

Set the following DHCP scope options: DNS server, domain, and default gateway address:

Set-DhcpServerv4OptionValue -ScopeID 192.168.113.0 -DnsDomain woshub.com -DnsServer 192.168.13.4 -Router 192.168.113.1

Add exceptions to DHCP scope:

Add-DhcpServerv4ExclusionRange -ScopeID 192.168.113.0 -StartRange 192.168.113.90 -EndRange 192.168.113.100

Activate DHCP scope:

Set-DhcpServerv4Scope -ScopeID 192.168.113.0 -State Active

Add-DhcpServerv4Scope - create and configure new dhcp scope using PowerShell

For convenience, you can use the following PowerShell command when creating a new scope:
$HashArgs = @{
'Name' = 'NY Office Scope';
'Description' = 'Workstations';
'StartRange' = '192.168.120.10';
'EndRange' = '192.168.120.200';
'SubnetMask' = '255.255.255.0';
'State' = 'Active';
'LeaseDuration' = '7.00:00:00';
}
Add-DhcpServerv4Scope @HashArgs

You can add other DHCP server options (e. g., WPAD) as follows:

Add-DhcpServerv4OptionDefinition -ComputerName be-dhcp1 -Name WPAD -OptionId 252 -Type String

You can display a list of configured DHCP server options:

Get-DHCPServerv4OptionValue -ComputerName be-dhcp1 | Format-List

Display a list of configured scope options:

Get-DHCPServerv4OptionValue -ComputerName be-dhcp1 -ScopeId 192.168.12.0 | Format-List

Show the current list of leased IP addresses for the DHCP scope 192.168.12.0:

Get-DHCPServerv4Lease -ScopeId 192.168.12.0 -ComputerName be-dhcp1

Get-DHCPServerv4Lease

Create a DHCP reservation for a client who is assigned a dynamic IP address 192.168.12.88 (convert the leased IP address to a reserved one):

Get-DhcpServerv4Lease -ComputerName be-dhcp1 -IPAddress 192.168.12.88| Add-DhcpServerv4Reservation -ComputerName be-dhcp1

You can perform a bulk reservation of IP addresses for computers listed in a CSV file. To do it, create a text file in the following format:

ScopeId,IPAddress,Name,ClientId,Description
192.168.12.0,192.168.12.88,PC-be-s1,2a-a2-1c-39-42-1f,Reservation PC-be-s1
192.168.12.0,192.168.12.89,PC-be-s2,2a-a2-1c-59-22-2f,Reservation PC-be-s2

Save the file as c:\dhcp\DHCPReservations.csv and run the following command, which will import data from the CSV file and create DHCP reservations for clients:

Import-Csv –Path c:\dhcp\DHCPReservations.csv | Add-DhcpServerv4Reservation -ComputerName be-dhcp1

Deactivate a scope on a DHCP server:

Set-DhcpServerv4Scope -ComputerName be-dhcp1 -ScopeId 192.168.12.0 -State InActive

Remove a scope from a DHCP server:

Remove-DHCPServerv4Scope -ComputerName be-dhcp1 -ScopeId 192.168.12.0 -Force

You can get DHCP server statistics (the number of scopes and reservations, the percentage of used addresses, etc.).

Get-DhcpServerv4Statistics -ComputerName be-dhcp1

Get-DhcpServerv4Statistics

The same information for a specific scope can be obtained using the Get-DhcpServerv4ScopeStatistics cmdlet.

DHCP server configuration can be exported to the XML file with the following command:

Export-DHCPServer -ComputerName be-dhcp1 -File C:\dhcp\dhcp-export.xml

Hint. You can use this command in Task Scheduler to back up the DHCP server configuration.

Further, these DHCP server settings can be imported (transferred) to another DHCP server:

Import-DHCPServer -ComputerName be-dhcp2 -File C:\dhcp\dhcp-export.xml -BackupPath C:\dhcpbackup\

You need to have an Active Directory domain in place. I’m picking up where I left off in my previous
blog article
Use PowerShell to Create a New Active Directory Forest on Windows 2019 Server Core Installation (no-GUI).

The procedure shown in this blog article is for demonstration purposes only.

Install the DHCP server feature.

1Install-WindowsFeature -Name DHCP

dhcpserver1a.jpg

Add the DHCP scope to the server.

1Add-DhcpServerv4Scope -Name '192.168.129.x' -StartRange 192.168.129.101 -EndRange 192.168.129.199 -SubnetMask 255.255.255.0

dhcpserver2a.jpg

Options can either be set at the scope level.

1Set-DhcpServerv4OptionValue -ScopeID '192.168.129.0' -DNSServer 192.168.129.100 -DNSDomain mikefrobbins.com -Router 192.168.129.1

dhcpserver3a.jpg

Or at the server level.

1Set-DhcpServerv4OptionValue -DNSServer 192.168.129.0 -DNSDomain mikefrobbins.com -Router 192.168.129.1

dhcpserver4a.jpg

Authorize the DHCP server.

1Add-DhcpServerInDC -DnsName dc01.mikefrobbins.com

dhcpserver5a.jpg

Display information about the scope.

1Get-DhcpServerv4Scope | Select-Object -Property *

dhcpserver6a.jpg

Warning: Do NOT connect a DHCP server to your production network without explicit permission
from your corporate network team .

warning.png

The procedure shown in this blog article was deployed to an isolated Hyper-V internal network in a
test lab.

µ

Network nodes require an IP address configuration that usually comprises the IP address, subnet mask, default gateway IP for the router, name servers and other values.

Administrators can manually set this information, resulting in a static configuration. A Dynamic Host Configuration Protocol (DHCP) server can also dynamically provide the information.

Generally, servers, routers, network printers and other such devices have a static configuration. Workstations, laptops, phones, tablets and other end-user devices receive their configuration via DHCP.

Client devices lease their IP address configuration by using the following four-step DORA process:

  1. Discover. The client broadcasts an attempt to discover a DHCP server.
  2. Offer. DHCP servers that receive the client broadcast offer an IP address configuration.
  3. Request. The client formally requests the IP configuration from the first DHCP server to respond.
  4. Acknowledge. The DHCP server acknowledges the lease and doesn’t offer that same address to another client.

The lease must be renewed by the client periodically.

Now that we’ve briefly reviewed how IP addresses are allocated and the lease generation process, let’s delve into more detail about how to configure the Windows Server DHCP service.

1. Install DHCP on Windows Server 2019

The DHCP service is not automatically installed on Windows Server 2019. It is easy to add, however, using either Server Manager or Windows PowerShell.

To add DHCP using Server Manager, select Add Roles and Features, and then select DHCP in the Roles list.

To add the DHCP role using the command line, open Windows PowerShell (Admin), and type the following:

Install-WindowsFeature DHCP -IncludeManagementTools

Windows PowerShell DHCP installation screenshot

Install the DHCP role by using Windows PowerShell.

The installation takes about one minute to complete.

Once admins install the DHCP service, they can manage it by selecting Tools > DHCP.

2. Authorize DHCP in Active Directory

Windows-based DHCP servers must be registered with Active Directory (AD) before they begin offering IP address configurations to clients.

Right-click on the server node in the DHCP console, and select Authorize to accomplish this authorization. You need Enterprise Admin privileges to authorize DHCP.

3. Create a scope

Before building the first pool of available IP addresses, it’s critical to plan the deployment. Devices, such as servers, routers and even printers, may have static IP address configuration. Make sure you have identified these addresses and that you allow for them in scope. Many administrators place all statically assigned IP addresses at the front of the scope.

Here is a simple example design:

  • Scope address range: 192.168.2.0/24
  • Static IP addresses: 192.168.2.1 through 192.168.2.25 (be sure to leave some room for additional devices)
  • Dynamic IP addresses: 192.168.2.26 through 192.168.2.254

You also need to gather additional configuration details, including the following:

  • Name and description. The scope name and an optional description.
  • Default gateway value. The IP address of the network interface card in the router attached to this network.
  • Name resolution servers. The IP address of one or more DNS servers.
  • Reservations. Any IP addresses that are dynamically allocated to specific clients, enabling those clients to acquire a consistent IP configuration from DHCP.
  • Lease time. The time the IP address lease is valid. It needs to be renewed at the halfway point of the lease. The Windows Server DHCP default is eight days.

4. Configure and activate the scope

Once you have documented the above values, you can configure the scope. Right-click the server node in the DHCP console, and then select New Scope. A wizard prompts you for the information you collected above. These settings can be changed later.

New DHCP scope screenshot

Create a new DHCP scope.

Once activated, the DHCP server begins responding to DHCP client discover messages by offering IP addresses. The scope can be deactivated, the DHCP service can be stopped or restarted, and the DHCP server can be deauthorized in AD.

5. DNS registration

DNS relates easy-to-remember hostnames with difficult-to-remember IP addresses. This database can be populated in several ways.

One method is to configure the DHCP server to create resource records for the client. The DHCP server can be set to create A records (hostname to IP address), pointer (PTR) records (IP to hostname) or both.

The default is for DHCP to create the PTR record, while the client itself registers its record with DNS.

screenshot of DNS configuration for DHCP

Configure DNS options.

Administrative DHCP tasks

The DHCP service is simple to configure. But sys admins often find some additional settings to be useful.

Create reservation

In some cases, it’s useful to allow a client machine to maintain a consistent IP address. While you could set the IP address configuration statically, it’s often better to reserve the IP address for the client in DHCP. The client goes through the DORA process to receive its settings, so values, such as router and name resolution servers, can still be updated via DHCP.

screenshot of IP address reservation

Reserve an IP address for the Dev-Computer.

DHCP failover

With Windows Server 2012, Microsoft introduced DHCP failover. It seems many administrators are unaware of this capability. Configuration is straightforward and requires no special software.

To configure DHCP failover, use the following steps:

  1. Ensure the DHCP role is installed on both DHCP servers and that they have network connectivity with each other.
  2. Configure a DHCP scope on one of the servers.
  3. Right-click the scope, and select DHCP Failover from the context menu.
  4. Complete the wizard.
  5. Select the second DHCP server, and observe that the new scope appears.

screenshot of DHCP failover configuration

Configure DHCP failover.

Logs

Managing service log files is a standard function for sys admins. DHCP writes messages to Event Viewer and to text files.

Sys admins can check the system log for general DHCP and network messages. They can find DHCP entries by drilling down to Applications and Services > Microsoft > Windows > DHCP-Server > Microsoft-Windows-DHCP-Server-Events > Operational.

DHCP also generates text-based log files stored at C:\Windows\System32\dhcp. These logs are extremely useful for troubleshooting. They can display information for why the server was unable to lease configurations to clients.

screenshot of DHCP text logs

DHCP text logs

Note that the text file logs are named based on days of the week and are overwritten weekly. If you want to retain these logs, you must rename them before the upcoming day of the week can overwrite them.

The DHCP role is not installed by default, so the first step is to add it. From there, create a new scope based on your plan.

Be careful of conflicting scopes

As more subnets — and, therefore, more DHCP scopes — are added to the network, it’s imperative that sys admins accurately document the IP address ranges. Overlapping scopes, where two DHCP servers are offering the same IP addresses to clients, result in a variety of network communications issues.

This is part of the reason why Microsoft requires DHCP servers to be authorized in AD. That authorization can only be implemented by Enterprise Admins, who should have enough broad knowledge of network configuration to prevent conflicting scopes.

Avoid duplicate IP address offers

One of the most serious misconfigurations is a client computer configured with a static IP address that falls within the DHCP server’s scope. In that case, the server can offer the IP address to a client because it is unaware of the static IP. This results in an IP address conflict.

The Windows DHCP service can be configured to ping an IP address before offering it to a client. If the ping returns a response, the DHCP server knows the address is already in use and should not be offered. The server offers a different address to the client.

screenshot of configuring conflict detection attempts

Configure conflict detection attempts.

The ping request occurs between the Discover and Offer steps of the lease generation process. It introduces a significant delay, so only configure this setting if you have a real concern about undocumented static IP addresses on client devices.

Conclusion

Microsoft has made the configuration of a DHCP server straightforward. Make sure you have a solid understanding of the entire network’s IP address configurations before you begin and plan your scope around both dynamic and static IP address assignments.

The DHCP role is not installed by default, so the first step is to add it. From there, create a new scope based on your plan. Add any options, such as DNS and reserved addresses. Review log files regularly. DHCP is simple but critical for network communication.

  • Apr 20, 2020

  • 24k

I have created a Windows core server named TM_DHCP. The below image is showing the Server configuration. To open the server configuration use the “Sconfig” command in PowerShell. The server is already part of the test domain.

DHCP Role On Windows 2019 Core

First, we will install DHCP using the windows admin Center. I have added that to Windows Admin Center for easy management.

DHCP Role On Windows 2019 Core

Under Roles and Feature, select DHCP and click install.

DHCP Role On Windows 2019 Core

It will remotely calculate the dependencies for the DHCP role on the server.

DHCP Role On Windows 2019 Core

Once the checks complete, it will start installing the DHCP role on the server.

DHCP Role On Windows 2019 Core

It will take a few minutes for the role to get installed.

DHCP Role On Windows 2019 Core

To manage more using PowerShell, install the DHCP PowerShell tools. 

DHCP Role On Windows 2019 Core

Now we can configure the DHCP server using Windows Admin Center.

DHCP Role On Windows 2019 Core

The second method is to install DHCP using PowerShell on Windows server 2019 core.

Open PowerShell as administrator and run the below command to install the DHCP role on the server.

Install-WindowsFeature DHCP -IncludeManagementTools

DHCP Role On Windows 2019 Core

Once the DHCP install is complete, we will start the configuration.

First, we will create a DHCP security group using the netsh command.

netsh DHCP add securitygroups

DHCP Role On Windows 2019 Core

Restart-Service dhcpserver

DHCP Role On Windows 2019 Core

Authorize the DHCP server in Active Directory using “add-DhcpServerInDC” command.

Add-DhcpServerInDC -DnsName TM-DHCP.Domain.com -IPAddress 10.0.64.7

DHCP Role On Windows 2019 Core

Use Get-DHcpServerInDc to verify the DHCP server authorized in Active Directory.

Get-DHcpServerInDc

DHCP Role On Windows 2019 Core

To assign IP to the requesting system, we now have to create Scope. With the scope, we will also configure the DHCP options like DHCP Exclusion range, Default gateway, DNS server IP address, and DNS domain name.

Add-DhcpServerv4Scope -name «Internal» -StartRange 10.0.64.1 -EndRange 10.0.64.254 -SubnetMask 255.255.255.0 -State Active

DHCP Role On Windows 2019 Core

Add-DhcpServerv4ExclusionRange -ScopeID 10.0.64.0 -StartRange 10.0.64.1 -EndRange 10.0.64.10

DHCP Role On Windows 2019 Core

Set-DhcpServerv4OptionValue -OptionID 3 -Value 10.0.64.1 -ScopeID 10.0.64.0 -ComputerName TM-DHCP.Domain.com

DHCP Role On Windows 2019 Core

Set-DhcpServerv4OptionValue -DnsDomain teammicro.dom -DnsServer 10.0.64.5

DHCP Role On Windows 2019 Core

To test the new DHCP server, I used two different systems, Windows Core and Windows 10 for the IP assignment using the newly-created DHCP server.

DHCP Role On Windows 2019 CoreDHCP Role On Windows 2019 Core

Below is the Windows Admin Center view to check the configuration on the DHCP server.

DHCP Role On Windows 2019 Core

Now the DHCP server is up and ready for use.

Conclusion

We have covered the Step by Step install and configuration process for the DHCP role on Windows server 2019 core.

Thank you for reading. 

Recommended Free Ebook

C# Corner Ebook

  • Настройка ip адреса на компьютере windows 7
  • Настройка flash player windows 10
  • Настройка dhcp сервера windows server 2016
  • Настройка firewall windows server 2019
  • Настройка dhcp windows server vlan