Mastering Bandwidth Control for Windows Updates with PowerShell

Key Takeaways

  • The script allows IT professionals to set bandwidth limits for Windows and Microsoft Store updates.
  • It uses PowerShell to modify Windows Registry settings for controlling update traffic.
  • Environment variables can influence the script’s behavior if already set for bandwidth limits.
  • The script includes error handling to ensure that users specify the required speed limits.
  • Bandwidth limits are defined using the BackgroundSpeed and ForegroundSpeed parameters.
  • A privilege check is performed to ensure the script runs with administrative rights.
  • It offers a more flexible and automatable alternative to manual Group Policy settings.
  • Appropriate bandwidth management is crucial to avoid network congestion and ensure the efficient running of critical applications.
  • The script should be tested in a controlled environment before widespread implementation.

Managing network bandwidth effectively is a critical aspect of IT infrastructure management, particularly in environments where resources are shared and network performance is paramount. With the increasing volume of data transferred during system updates or while using cloud-based services, controlling bandwidth usage becomes essential to maintain network stability and efficiency.

Background

The PowerShell script we are discussing plays a vital role in this context. It provides a solution for IT professionals and Managed Service Providers (MSPs) to limit bandwidth usage for Windows updates and Microsoft Store updates on devices. This functionality is particularly crucial for organizations that face bandwidth limitations or need to prioritize network traffic for critical applications. By controlling update traffic, IT professionals can prevent network congestion and ensure that business-critical applications get the necessary bandwidth.

The Script:

#Requires -Version 5.1

<#
.SYNOPSIS
    Limit how much bandwidth a device can consume with updates and microsoft store updates. Please note 5Mbps will set a different speed limit than 5MBps.
.DESCRIPTION
    Limit how much bandwidth a device can consume with updates and microsoft store updates. Please note 5Mbps will set a different speed limit than 5MBps.
.EXAMPLE
    (No Parameters)

    C:ProgramDataNinjaRMMAgentscriptingcustomscript_gen_6.ps1 : No Speed Limit given?
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,customscript_gen_6.ps1

PARAMETER: -BackgroundSpeed "15Mbps"
    Limits the "background" bandwidth to 15Mbps replace "15Mbps" with your prefered speed limit.
.EXAMPLE
    -BackgroundSpeed "15Mbps"
    
    HKLM:SOFTWAREPoliciesMicrosoftWindowsDeliveryOptimizationDOMaxBackgroundDownloadBandwidth changed from 1920 to 1920

PARAMETER: -ForegroundSpeed "15Mbps"
    Limits the "foreground" bandwidth to 15Mbps replace "15Mbps" with your prefered speed limit.
.EXAMPLE
    -ForegroundSpeed "15Mbps"
    
    HKLM:SOFTWAREPoliciesMicrosoftWindowsDeliveryOptimizationDOMaxForegroundDownloadBandwidth changed from 1920 to 1920

.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10
    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 (
    [Parameter()]
    [String]$BackgroundSpeed,
    [Parameter()]
    [String]$ForegroundSpeed
)

begin {

    if ($env:maxBackgroundDownloadSpeed -and $env:maxBackgroundDownloadSpeed -notlike "null") { $BackgroundSpeed = $env:maxBackgroundDownloadSpeed }
    if ($env:maxForegroundDownloadSpeed -and $env:maxForegroundDownloadSpeed -notlike "null") { $ForegroundSpeed = $env:maxForegroundDownloadSpeed }

    if (-not $BackgroundSpeed -and -not $ForegroundSpeed) {
        Write-Error "No Speed Limit given?"
        Exit 1
    }

    function Set-HKProperty {
        param (
            $Path,
            $Name,
            $Value,
            [ValidateSet('DWord', 'QWord', 'String', 'ExpandedString', 'Binary', 'MultiString', 'Unknown')]
            $PropertyType = 'DWord'
        )
        if (-not $(Test-Path -Path $Path)) {
            # Check if path does not exist and create the path
            New-Item -Path $Path -Force | Out-Null
        }
        if ((Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue)) {
            # Update property and print out what it was changed from and changed to
            $CurrentValue = (Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue).$Name
            try {
                Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Error "[Error] Unable to Set registry key for $Name please see below error!"
                Write-Error $_
                exit 1
            }
            Write-Host "$Path$Name changed from $CurrentValue to $($(Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue).$Name)"
        }
        else {
            # Create property with value
            try {
                New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Error "[Error] Unable to Set registry key for $Name please see below error!"
                Write-Error $_
                exit 1
            }
            Write-Host "Set $Path$Name to $($(Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue).$Name)"
        }
    }

    function Get-Size {
        param (
            [string]$String
        )
        if ($String -Like 0) {
            return 0
        }
        switch -casesensitive -regex ($String) {
            'PB|pB' { [int64]$($String -replace '[^d+]+') * 1PB; break }
            'Pb|pb' { [int64]$($String -replace '[^d+]+') * 1PB / 8; break }
            'TB|tB' { [int64]$($String -replace '[^d+]+') * 1TB; break }
            'Tb|tb' { [int64]$($String -replace '[^d+]+') * 1TB / 8; break }
            'GB|gB' { [int64]$($String -replace '[^d+]+') * 1GB; break }
            'Gb|gb' { [int64]$($String -replace '[^d+]+') * 1GB / 8; break }
            'MB|mB' { [int64]$($String -replace '[^d+]+') * 1MB; break }
            'Mb|mb' { [int64]$($String -replace '[^d+]+') * 1MB / 8; break }
            'KB|kB' { [int64]$($String -replace '[^d+]+') * 1KB; break }
            'Kb|kb' { [int64]$($String -replace '[^d+]+') * 1KB / 8; break }
            'B|b' { [int64]$($String -replace '[^d+]+') * 1; break }
            Default { [int64]$($String -replace '[^d+]+') * 1MB / 8 }
        }
    }

    function ConvertTo-Kilobytes {
        param (
            [Parameter(ValueFromPipeline)]
            $Number
        )
        process {
            $Number / 1KB
        }
    }

    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }

    $Path = "HKLM:SOFTWAREPoliciesMicrosoftWindowsDeliveryOptimization"
    if ($BackgroundSpeed) { Set-HKProperty -Path $Path -Name DOMaxBackgroundDownloadBandwidth -Value $(Get-Size $BackgroundSpeed | ConvertTo-Kilobytes ) }
    if ($ForegroundSpeed) { Set-HKProperty -Path $Path -Name DOMaxForegroundDownloadBandwidth -Value $(Get-Size $ForegroundSpeed | ConvertTo-Kilobytes ) }
}
end {
    
    
    
}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

The script operates in several key stages:

  • Parameter Definition: It starts by defining two parameters – BackgroundSpeed and ForegroundSpeed. These parameters allow users to set limits for background and foreground data transfer rates, respectively.
  • Environment Variable Check: The script checks for existing environment variables that might already set these parameters, ensuring it doesn’t overwrite preconfigured settings.
  • Error Handling: If no speed limits are given, the script raises an error, prompting the user to input the required parameters.
  • Registry Modification Functions: The core functionality lies in the Set-HKProperty function, which modifies Windows Registry keys to enforce the bandwidth limits. It creates or updates the relevant registry entries with the specified values.
  • Bandwidth Calculation: The Get-Size function interprets the speed limits entered by the user, converting them into a format understood by the registry (kilobytes).
  • Execution and Privilege Check: Before applying any changes, the script checks if it’s running with administrative privileges, a necessity for modifying registry settings.

Potential Use Cases

Consider a scenario in an educational institution where network bandwidth is a premium during school hours. The IT administrator can use this script to limit Windows Update bandwidth during these hours, ensuring that online educational resources receive priority. Post-school hours, these limitations can be relaxed or removed for regular updates.

Comparisons

Traditionally, bandwidth limits for Windows updates were managed either manually through Group Policy Editor or via third-party software. This script provides a more direct and scriptable approach, allowing for automation and integration into larger IT management workflows.

FAQs

  • How does this script differ from using Group Policy?
    The script offers a more flexible and automatable approach compared to the manual settings in Group Policy.
  • Can this script handle unlimited bandwidth scenarios?
    Yes, setting the speed parameter to 0 allows for unlimited bandwidth usage.

Implications

Using this script can greatly enhance network performance management. However, improperly setting bandwidth limits might delay critical updates, potentially exposing systems to security vulnerabilities. Thus, a balanced approach is necessary.

Recommendations

  • Test the script in a controlled environment before deploying it broadly.
  • Monitor network performance and adjust limits as necessary.
  • Keep security implications in mind when delaying updates.

Final Thoughts

In the world of managed IT services, where tools like NinjaOne offer comprehensive solutions, scripts like this enhance control and flexibility. They enable IT professionals to tailor network performance to their specific needs, a critical advantage in today’s fast-paced, data-driven environment. Integrating such scripts into broader IT management frameworks can significantly boost efficiency and effectiveness in managing IT infrastructure.

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

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).