Comprehensive Guide to Monitoring DHCP Leases with PowerShell

Want to learn more about DHCP lease notifications for PowerShell? This article will explain why monitoring and managing DHCP scopes is a critical task for IT professionals and Managed Service Providers (MSPs). Ensuring that DHCP servers are functioning efficiently and that there are enough available IP addresses in the pool can prevent network issues and ensure seamless connectivity.

This blog post delves into a PowerShell script designed to monitor DHCP scopes, alerting administrators when the number of available leases falls below a specified threshold. This script is an essential tool for maintaining network reliability and avoiding potential disruptions.

Background

Dynamic Host Configuration Protocol (DHCP) is a network management protocol used to automate the process of configuring devices on IP networks. Without DHCP, each device on the network would need to be manually assigned an IP address. Given the dynamic nature of modern networks, DHCP servers are often under constant demand to provide IP addresses.

Monitoring these servers and ensuring they have sufficient leases available is crucial. The provided PowerShell script addresses this need by checking the DHCP scopes and alerting administrators if the number of free leases falls below a certain threshold.

The Script:

#Requires -Version 5.1

<#
.SYNOPSIS
    Checks the DHCP scopes for the number of leases used and alerts if the threshold is exceeded.
.DESCRIPTION
    Checks the DHCP scopes for the number of leases used and alerts if the threshold is exceeded.
    This script requires the DhcpServer module to be installed with the DHCP server feature installed.
    The script will output the number of leases used, free, and total for each scope.
    If the LeaseThreshold parameter is set, the script will alert if the number of free leases is less than the threshold.
    If the ExcludeScope parameter is set, the script will exclude the specified scope from the output.
    If the IncludeScope parameter is set, the script will only include the specified scope in the output.

.PARAMETER LeaseThreshold
    The number of free leases that will trigger an alert. If the number of free leases is less than the threshold, an alert will be triggered.
.PARAMETER ExcludeScope
    The name of the scope to exclude from the output.
.PARAMETER IncludeScope
    The name of the scope to include in the output.

.EXAMPLE
    (No Parameters)
    ## EXAMPLE OUTPUT WITHOUT PARAMS ##
    [Info] Scope: Test1 Leases Used(In Use/Total): 250/252
    [Info] Scope: Test2 Leases Used(In Use/Total): 220/252
    [Info] Scope: Test6 Leases Used(In Use/Total): 4954378/18446744073709551615

.EXAMPLE
    PARAMETER: -LeaseThreshold 10
    ## EXAMPLE OUTPUT WITH LEASETHRESHOLD ##
    [Alert] Scope: Test1 Leases Used(In Use/Free/Total): 220/2/252
    [Info] Scope: Test2 Leases Used(In Use/Free/Total): 150/102/252
    [Info] Scope: Test6 Leases Used(In Use/Free/Total): 0/18446744073709551615/18446744073709551615

.EXAMPLE
    PARAMETER: -ExcludeScope "Test1"
    ## EXAMPLE OUTPUT WITH EXCLUDESCOPE ##
    [Info] Scope: Test2 Leases Used(In Use/Free/Total): 220/2/252
    [Info] Scope: Test6 Leases Used(In Use/Free/Total): 0/18446744073709551615/18446744073709551615

.EXAMPLE
    PARAMETER: -IncludeScope "Test2"
    ## EXAMPLE OUTPUT WITH INCLUDESCOPE ##
    [Info] Scope: Test2 Leases Used(In Use/Free/Total): 220/2/252
.NOTES
    Minimum OS: Windows Server 2016
    Requires the DhcpServer module to be installed with the DHCP server feature installed.
    Release Notes: Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param (
    $LeaseThreshold,
    [string[]]$ExcludeScope,
    [string[]]$IncludeScope
)

begin {
    function Test-IsElevated {
        # check if running under a Pester test case
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    try {
        if ($env:leaseThreshold -and $env:leaseThreshold -notlike "null") {
            [int]$LeaseThreshold = $env:leaseThreshold
        }
    }
    catch {
        Write-Host "[Error] LeaseThreshold must be a number"
        exit 2
    }
    
    if ($env:excludeScope -and $env:excludeScope -notlike "null") {
        $ExcludeScope = $env:excludeScope
    }
    if ($env:includeScope -and $env:includeScope -notlike "null") {
        $IncludeScope = $env:includeScope
    }

    # Split the ExcludeScope and IncludeScope parameters into an array
    if (-not [String]::IsNullOrWhiteSpace($ExcludeScope) -and $ExcludeScope -like '*,*') {
        $ExcludeScope = $ExcludeScope -split ',' | ForEach-Object { $_.Trim() } | Where-Object { -not [String]::IsNullOrWhiteSpace($_) } | Sort-Object -Unique
    }
    if (-not [String]::IsNullOrWhiteSpace($IncludeScope) -and $IncludeScope -like '*,*') {
        $IncludeScope = $IncludeScope -split ',' | ForEach-Object { $_.Trim() } | Where-Object { -not [String]::IsNullOrWhiteSpace($_) } | Sort-Object -Unique
    }

    # Check if $ExcludeScope and $IncludeScope contain similar items
    if (-not [String]::IsNullOrWhiteSpace($ExcludeScope) -and -not [String]::IsNullOrWhiteSpace($IncludeScope)) {
        $SimilarItems = $ExcludeScope | Where-Object { $IncludeScope -contains $_ }
        if ($SimilarItems) {
            Write-Host "[Error] The following scopes are in both ExcludeScope and IncludeScope: $($SimilarItems -join ', ')"
            exit 2
        }
    }

    $ShouldAlert = $false
}
process {
    if (-not (Test-IsElevated)) {
        Write-Host "[Error] Access Denied. Please run with Administrator privileges."
        exit 2
    }

    # Check if the DhcpServer module is installed
    if (-not (Get-Module -ListAvailable -Name DhcpServer -ErrorAction SilentlyContinue)) {
        Write-Host "[Error] The DhcpServer module is not installed. Please install the DHCP server feature and the DhcpServer module."
        exit 2
    }

    # Get all DHCP scopes
    $AllScopes = $(
        Get-DhcpServerv4Scope | Select-Object -ExpandProperty Name
        Get-DhcpServerv6Scope | Select-Object -ExpandProperty Name
    )

    # Output an error if the ExcludeScope or IncludeScope parameters contain invalid scope names
    $(
        if ($IncludeScope) { $IncludeScope }
        if ($ExcludeScope) { $ExcludeScope }
    ) | ForEach-Object {
        if ($_ -notin $AllScopes) {
            Write-Host "[Error] Scope: $_ does not exist in the DHCP server. Please check the scope name and try again."
        }
    }

    # IPv4
    # Get all DHCP scopes
    $v4scopes = Get-DhcpServerv4Scope | Where-Object { $_.State }

    # Iterate through each scope
    foreach ($scope in $v4scopes) {
        # Get statistics for the scope
        $Stats = Get-DhcpServerv4ScopeStatistics -ScopeId $scope.ScopeId

        # Get the name of the scope
        $Name = (Get-DhcpServerv4Scope -ScopeId $scope.ScopeId).Name

        # Check if the scope should be excluded
        if (-not [String]::IsNullOrWhiteSpace($ExcludeScope) -and $Name -in $ExcludeScope) {
            continue
        }

        # Check if the scope should be included
        if (-not [String]::IsNullOrWhiteSpace($IncludeScope) -and $Name -notin $IncludeScope) {
            continue
        }

        # Check if the number of free leases is less than the threshold
        if ($Stats.Free -lt $LeaseThreshold ) {
            if ($ShouldAlert -eq $false) {
                # Output once if this is the first scope to trigger an alert
                Write-Host "[Alert] Available DHCP Leases Low. You may want to make modifications to one of the below scopes."
            }
            Write-Host "[Alert] Scope: $Name Leases Used(In Use/Free/Total): $($Stats.InUse)/$($Stats.Free)/$($Stats.InUse+$Stats.Free)"
            $ShouldAlert = $true
        }
        else {
            Write-Host "[Info] Scope: $Name Leases Used(In Use/Free/Total): $($Stats.InUse)/$($Stats.Free)/$($Stats.InUse+$Stats.Free)"
        }
    }

    # IPv6
    # Get all DHCP scopes
    $v6Scopes = Get-DhcpServerv6Scope | Where-Object { $_.State }

    # Iterate through each scope
    foreach ($scope in $v6Scopes) {
        # Get statistics for the scope
        $Stats = Get-DhcpServerv6ScopeStatistics -Prefix $scope.Prefix

        # Get the name of the scope
        $Name = (Get-DhcpServerv6Scope -Prefix $scope.Prefix).Name

        # Check if the scope should be excluded
        if (-not [String]::IsNullOrWhiteSpace($ExcludeScope) -and $Name -in $ExcludeScope) {
            continue
        }

        # Check if the scope should be included
        if (-not [String]::IsNullOrWhiteSpace($IncludeScope) -and $Name -notin $IncludeScope) {
            continue
        }

        # Check if the number of free leases is less than the threshold
        if ($Stats.Free -lt $LeaseThreshold ) {
            if ($ShouldAlert -eq $false) {
                # Output once if this is the first scope to trigger an alert
                Write-Host "[Alert] Available DHCP Leases Low. You may want to make modifications to one of the below scopes."
            }
            Write-Host "[Alert] Scope: $Name Leases Used(In Use/Free/Total): $($Stats.InUse)/$($Stats.Free)/$($Stats.InUse+$Stats.Free)"
            $ShouldAlert = $true
        }
        else {
            Write-Host "[Info] Scope: $Name Leases Used(In Use/Free/Total): $($Stats.InUse)/$($Stats.Free)/$($Stats.InUse+$Stats.Free)"
        }
    }

    exit 0

}
end {
    
    
    
}

 

Detailed Breakdown

This PowerShell script requires the DhcpServer module and is compatible with Windows Server 2016 or later. Here’s a step-by-step explanation of how it works:

Parameters

  • LeaseThreshold: This parameter sets the minimum number of free leases required before triggering an alert.
  • ExcludeScope: Specifies DHCP scopes to exclude from the monitoring.
  • IncludeScope: Specifies DHCP scopes to include in the monitoring.

Initial Setup

The script begins by defining a function to check if it is running with administrator privileges, which is necessary for accessing DHCP server data. It then processes any environment variables for the LeaseThreshold, ExcludeScope, and IncludeScope parameters, ensuring they are correctly formatted.

Excluding and Including Scopes

The script splits and processes the ExcludeScope and IncludeScope parameters, converting them into arrays. It ensures there are no overlaps between the two lists, which could cause conflicts.

Checking DHCP Scopes

The script retrieves all available DHCP scopes (both IPv4 and IPv6). It then filters these scopes based on the ExcludeScope and IncludeScope parameters. For each scope, the script fetches the statistics, including the number of used and free leases.

Alerting

If the number of free leases in any scope falls below the LeaseThreshold, the script outputs an alert message. This ensures that administrators are immediately aware of any potential issues with DHCP lease availability.

Finalizing

If the script encounters any errors, such as missing modules or invalid scope names, it outputs an appropriate error message and exits.

Potential Use Cases

Imagine an IT professional managing a network for a large organization. They have multiple DHCP servers spread across different locations. Each server manages several scopes, and it’s critical to ensure there are always enough IP addresses available for new devices. By implementing this script, the IT professional can:

  1. Proactively Monitor DHCP Scopes: Regularly check the status of DHCP leases without manually reviewing each scope.
  2. Receive Alerts: Get instant notifications if any scope falls below a specified threshold of free leases, allowing for timely intervention.
  3. Efficient Resource Allocation: Adjust DHCP settings or add more IP addresses to scopes as needed, preventing network disruptions.

Comparisons

Script vs. Manual Monitoring

Manually monitoring DHCP scopes can be time-consuming and prone to human error. The script automates this process, providing consistent and reliable monitoring. Additionally, the script can handle multiple scopes and servers simultaneously, which would be challenging to manage manually.

Script vs. Third-Party Tools

While third-party tools offer comprehensive DHCP management solutions, they can be expensive and require additional infrastructure. This PowerShell script provides a cost-effective and straightforward solution for organizations looking to enhance their DHCP monitoring without significant investments.

FAQs

Q: What happens if the script is not run with administrator privileges?

A: The script will output an error message and exit. Administrator privileges are required to access DHCP server data.

Q: Can I use this script on older versions of Windows Server?

A: The script is designed for Windows Server 2016 or later. Earlier versions may not support the required DhcpServer module.

Q: What if the DHCP server module is not installed?

A: The script will output an error message indicating that the DhcpServer module is not installed. You will need to install the DHCP server feature and the DhcpServer module to use this script.

Implications

Effective DHCP scope monitoring can significantly enhance network reliability and security. By ensuring that there are always enough available IP addresses, network administrators can prevent connectivity issues and ensure seamless operation of network devices. This script helps identify potential issues before they escalate, allowing for proactive management and troubleshooting.

Recommendations

  • Regular Execution: Schedule the script to run at regular intervals using Task Scheduler or a similar tool to ensure continuous monitoring.
  • Threshold Adjustment: Set the LeaseThreshold parameter according to your network’s needs to avoid false alarms or missed alerts.
  • Scope Management: Regularly review and update the ExcludeScope and IncludeScope parameters to reflect changes in your network.

Final Thoughts

Monitoring DHCP scopes is a critical task for maintaining network reliability. This PowerShell script provides a powerful and efficient way to automate this process, ensuring that administrators are promptly alerted to potential issues. For IT professionals and MSPs, this script can be an invaluable tool in their network management toolkit.

Additionally, leveraging tools like NinjaOne can further enhance network monitoring and management, providing comprehensive solutions for maintaining IT infrastructure.

By implementing this script and following best practices, organizations can ensure their DHCP servers are always ready to meet network demands, preventing disruptions and maintaining smooth operations.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

How to Monitor Log Files on macOS with a Custom Bash Script

How to Monitor Log Files and Detect Specific Text on Linux Using a Bash Script

How to Use PowerShell to Monitor Text Files and Trigger Alerts for IT Professionals

How to Automate Microsoft Safety Scanner Using a PowerShell Script

Comprehensive Guide to Using PowerShell for Efficient Event Log Searches

How to Use PowerShell to Detect Open and Established Ports in Windows

Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).