Watch Demo×
×

See NinjaOne in action!

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

Enable or Disable Remote Desktop Protocol (RDP) on Workstations Using PowerShell

Key Takeaways

  • RDP is a crucial tool for IT professionals, allowing remote access to computers.
  • The provided PowerShell script offers a streamlined method to enable or disable RDP on workstations.
  • Two main actions are performed: modifying registry settings and adjusting firewall rules.
  • The script requires administrator privileges and checks if the machine is a workstation.
  • While RDP offers convenience, it can pose security risks if misconfigured.
  • Monitoring and using strong authentication methods are recommended for secure RDP usage.
  • Platforms like NinjaOne complement the script, offering a comprehensive IT management solution.

Remote Desktop Protocol (RDP) is an essential tool in the arsenal of IT professionals, allowing users to remotely connect to another computer over a network connection. But, like any powerful tool, RDP requires prudent management, especially as security concerns rise. This blog delves into a PowerShell script designed for managing and configuring Remote Desktop (RDP) settings on workstations.

Background

PowerShell has rapidly become a foundational tool for IT admins due to its flexibility and depth. The provided script taps into this potential by offering a concise method to enable or disable RDP for workstations. As IT environments become more complex, streamlined solutions like this script are indispensable for Managed Service Providers (MSPs) and IT professionals. Ensuring RDP is correctly configured is crucial, as any misconfiguration could expose vulnerabilities.

The Script

<#
.SYNOPSIS
    Enables or Disables RDP for workstations only.
.DESCRIPTION
    Enables or Disables RDP for workstations only.
.EXAMPLE
    -Disable
    Disables RDP for a workstation.
.EXAMPLE
    -Enable
    Enables RDP for a workstation.
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    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(DefaultParameterSetName = "Disable")]
param (
    [Parameter(Mandatory = $true, ParameterSetName = "Enable")]
    [switch]
    $Enable,
    [Parameter(Mandatory = $true, ParameterSetName = "Disable")]
    [switch]
    $Disable
)

begin {
    function Set-ItemProp {
        param (
            $Path,
            $Name,
            $Value,
            [ValidateSet("DWord", "QWord", "String", "ExpandedString", "Binary", "MultiString", "Unknown")]
            $PropertyType = "DWord"
        )
        # Do not output errors and continue
        $ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
        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)) {
            # Update property and print out what it was changed from and changed to
            $CurrentValue = Get-ItemProperty -Path $Path -Name $Name
            try {
                Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Error $_
            }
            Write-Host "$Path$Name changed from $CurrentValue to $Value"
        }
        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 $_
            }
            Write-Host "Set $Path$Name to $Value"
        }
        $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Continue
    }
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    # Registry settings
    $Path = 'HKLM:SYSTEMCurRentControlSetControlTerminal Server'
    $Name = "fDenyTSConnections"
    $RegEnable = 0
    $RegDisable = 1

    $osInfo = Get-CimInstance -ClassName Win32_OperatingSystem
    $IsWorkstation = if ($osInfo.ProductType -eq 1) {
        $true
    }
    else {
        $false
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    if (-not $IsWorkstation) {
        # System is a Domain Controller or Server
        Write-Error "System is a Domain Controller or Server. Skipping."
        exit 1
    }

    # Registry
    if ($Disable) {
        $RegCheck = $null
        $RegCheck = $(Get-ItemPropertyValue -Path $Path -Name $Name -ErrorAction SilentlyContinue)
        if ($null -eq $RegCheck) {
            $RegCheck = 0
        }
        if ($RegDisable -ne $RegCheck) {
            Set-ItemProp -Path $Path -Name $Name -Value $RegDisable
            Write-Host "Disabled $Path$Name"
        }
        else {
            Write-Host "$Path$Name already Disabled."
        }
    }
    elseif ($Enable) {
        $RegCheck = $null
        $RegCheck = $(Get-ItemPropertyValue -Path $Path -Name $Name -ErrorAction SilentlyContinue)
        if ($null -eq $RegCheck) {
            $RegCheck = 0
        }
        if ($RegEnable -ne $RegCheck) {
            Set-ItemProp -Path $Path -Name $Name -Value $RegEnable
            Write-Host "Enabled $Path$Name"
        }
        else {
            Write-Host "$Path$Name already Enabled."
        }
    }
    else {
        Write-Error "Enable or Disable was not specified."
        exit 1
    }

    # Firewall
    if ($Disable) {
        # Disable if was enabled and Disable was used
        try {
            Disable-NetFirewallRule -DisplayGroup "Remote Desktop" -ErrorAction Stop
        }
        catch {
            Write-Error $_
            Write-Host "Remote Desktop firewall group is missing?"
        }
        Write-Host "Disabled Remote Desktop firewall rule groups."
    }
    elseif ($Enable) {
        # Enable if was disabled and Enable was used
        try {
            Enable-NetFirewallRule -DisplayGroup "Remote Desktop" -ErrorAction Stop
        }
        catch {
            Write-Error $_
            Write-Host "Remote Desktop firewall group is missing?"
        }
        Write-Host "Enabled Remote Desktop firewall rule groups."
    }
    else {
        Write-Error "Enable or Disable was not specified."
        exit 1
    }
}
end {}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

  • Parameters: The script uses two parameters, Enable and Disable, which dictate whether the RDP should be turned on or off. These are mutually exclusive; only one can be used at a time.
  • Helper Functions: Two functions assist in the primary task:
  • Set-ItemProp: Updates or creates registry properties, handling potential errors and keeping the user informed.
  • Test-IsElevated: Checks if the script is run with administrator privileges.
  • Process: This is the script’s core. It starts by checking for administrator rights and if the machine is a workstation. It then proceeds to:
  • Modify the registry settings to enable or disable RDP.
  • Adjust the firewall settings to permit or block RDP traffic.

Potential Use Cases

Imagine a medium-sized company with multiple workstations for its employees. The IT department, for security purposes, has disabled RDP on all machines. However, an external consultant needs remote access to one workstation for diagnostics. Using this script, the IT admin can seamlessly enable RDP on that specific workstation and disable it once the task is done.

Comparisons

While there are GUI-based tools and other methods for managing RDP, the provided script offers the following advantages:

  • Scalability: Can be executed on multiple workstations via a script or task scheduler.
  • Flexibility: Easily integrated into more extensive IT workflows.
  • Transparency: By being open-source, the IT team can validate and adjust the script to fit specific needs.

FAQs

  • Can this script run on servers?
    No, the script specifically checks if the machine is a workstation before executing.
  • What happens if the script is run without admin privileges?
    An error message will display, prompting the user to run with administrator privileges.

Implications

While enabling RDP is convenient, an exposed RDP can be a significant security risk. Cybercriminals often exploit misconfigured RDPs. Thus, it’s imperative to balance convenience with security.

Recommendations

  • Always disable RDP when not in use.
  • Monitor RDP logs for any suspicious activities.
  • Employ strong authentication methods when RDP is enabled.

Final Thoughts

Tools like NinjaOne enhance IT operations, offering a centralized platform to manage and monitor networks, devices, and more. When integrating solutions like the discussed PowerShell script into broader IT frameworks, platforms such as NinjaOne provide invaluable oversight and efficiency.

By understanding and deploying PowerShell scripts like the one dissected above, IT professionals can bolster their efficiency and the security of their work environments. Combining this with powerful tools like NinjaOne makes IT management even more robust.

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

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