Watch Demo×
×

See NinjaOne in action!

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

Streamline UAC Audits in Windows with PowerShell

Key takeaways

  • Automated UAC auditing: The script offers an automated solution for auditing User Account Control settings on Windows systems.
  • Enhanced security: By ensuring UAC settings comply with security standards, the script significantly bolsters system security.
  • Custom field logging: Integrates with NinjaOne for logging UAC levels in custom fields, enhancing record-keeping and reporting.
  • Supports Windows 7 and later: The script is compatible with Windows 7, Windows Server 2012, and subsequent versions.
  • Administrator privileges required: Running this script necessitates administrative rights to access and modify registry settings.
  • Versatility in use: Ideal for MSPs and IT professionals for maintaining security across multiple systems.
  • Proactive risk mitigation: Regular use helps in proactively preventing unauthorized system changes.
  • Integration with managed services: Especially beneficial for those utilizing NinjaOne for centralized IT management.
  • Record keeping for compliance: Logs UAC settings, aiding in compliance with IT security policies and audits.

Introduction

User Account Control (UAC) is a crucial component in the Windows operating system, offering an added layer of security. It essentially limits application software to standard user privileges until an administrator authorizes an increase in privilege level. In the dynamic landscape of IT security, where vulnerabilities can be exploited by unauthorized users, maintaining optimal UAC settings is paramount. This blog post delves into a PowerShell script designed to audit and configure the UAC settings on a Windows machine, a tool of great significance for IT professionals and Managed Service Providers (MSPs).

Background

The script in question provides a comprehensive approach to auditing the UAC level on a Windows system. IT professionals and MSPs often require such tools to ensure that the systems they manage adhere to specific security standards. The script not only audits but also facilitates updating the UAC settings and can log these settings to a custom field for reporting purposes. Its capability to operate within the NinjaOne environment further enhances its utility in managed IT services.

The script:

#Requires -Version 2

<#
.SYNOPSIS
    Condition/Audit UAC Level. Can save the UAC Level to a custom field if specified.
.DESCRIPTION
    Condition/Audit UAC Level. Can save the UAC Level to a custom field if specified.

    Exit Code of 0 is that the UAC Level is set to the defaults or higher
    Exit Code of 1 is that the UAC Level is to lower than defaults
    Exit Code of 2 is when this fails to update a custom field
.EXAMPLE
     -CustomField "uac"
    Saves the UAC Level to a custom field.
.OUTPUTS
    String[]
.NOTES
    Minimum OS Architecture Supported: Windows 7, Windows Server 2012
    Release Notes: Renamed script and added Script Variable support
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]$CustomField
)

begin {
    if ($env:customFieldName -and $env:customFieldName -notlike "null") { $CustomField = $env:customFieldName }
    
    # https://learn.microsoft.com/en-us/windows/security/identity-protection/user-account-control/user-account-control-group-policy-and-registry-key-settings#registry-key-settings
    # Define the path in the registry
    $Path = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"

    # Define the values to check
    $Values = "FilterAdministratorToken",
    "EnableUIADesktopToggle",
    "ConsentPromptBehaviorAdmin",
    "ConsentPromptBehaviorUser",
    "EnableInstallerDetection",
    "ValidateAdminCodeSignatures",
    "EnableSecureUIAPaths",
    "EnableLUA",
    "PromptOnSecureDesktop",
    "EnableVirtualization"

    # This function is to make it easier to set Ninja Custom Fields.
    function Set-NinjaProperty {
        [CmdletBinding()]
        Param(
            [Parameter(Mandatory = $True)]
            [String]$Name,
            [Parameter()]
            [String]$Type,
            [Parameter(Mandatory = $True, ValueFromPipeline = $True)]
            $Value,
            [Parameter()]
            [String]$DocumentName
        )

        # If we're requested to set the field value for a Ninja document we'll specify it here.
        $DocumentationParams = @{}
        if ($DocumentName) { $DocumentationParams["DocumentName"] = $DocumentName }

        # This is a list of valid fields we can set. If no type is given we'll assume the input doesn't have to be changed in any way.
        $ValidFields = "Attachment", "Checkbox", "Date", "Date or Date Time", "Decimal", "Dropdown", "Email", "Integer", "IP Address", "MultiLine", "MultiSelect", "Phone", "Secure", "Text", "Time", "URL"
        if ($Type -and $ValidFields -notcontains $Type) { Write-Warning "$Type is an invalid type! Please check here for valid types. https://ninjarmm.zendesk.com/hc/en-us/articles/16973443979789-Command-Line-Interface-CLI-Supported-Fields-and-Functionality" }

        # The below field requires additional information in order to set
        $NeedsOptions = "Dropdown"
        if ($DocumentName) {
            if ($NeedsOptions -contains $Type) {
                # We'll redirect the error output to the success stream to make it easier to error out if nothing was found or something else went wrong.
                $NinjaPropertyOptions = Ninja-Property-Docs-Options -AttributeName $Name @DocumentationParams 2>&1
            }
        }
        else {
            if ($NeedsOptions -contains $Type) {
                $NinjaPropertyOptions = Ninja-Property-Options -Name $Name 2>&1
            }
        }

        # If we received some sort of error it should have an exception property and we'll exit the function with that error information.
        if ($NinjaPropertyOptions.Exception) { throw $NinjaPropertyOptions }

        # The below type's require values not typically given in order to be set. The below code will convert whatever we're given into a format ninjarmm-cli supports.
        switch ($Type) {
            "Checkbox" {
                # While it's highly likely we were given a value like "True" or a boolean datatype it's better to be safe than sorry.
                $NinjaValue = [System.Convert]::ToBoolean($Value)
            }
            "Date or Date Time" {
                # Ninjarmm-cli is expecting the time to be representing as a Unix Epoch string. So we'll convert what we were given into that format.
                $Date = (Get-Date $Value).ToUniversalTime()
                $TimeSpan = New-TimeSpan (Get-Date "1970-01-01 00:00:00") $Date
                $NinjaValue = $TimeSpan.TotalSeconds
            }
            "Dropdown" {
                # Ninjarmm-cli is expecting the guid of the option we're trying to select. So we'll match up the value we were given with a guid.
                $Options = $NinjaPropertyOptions -replace '=', ',' | ConvertFrom-Csv -Header "GUID", "Name"
                $Selection = $Options | Where-Object { $_.Name -eq $Value } | Select-Object -ExpandProperty GUID

                if (-not $Selection) {
                    throw "Value is not present in dropdown"
                }

                $NinjaValue = $Selection
            }
            default {
                # All the other types shouldn't require additional work on the input.
                $NinjaValue = $Value
            }
        }

        # We'll need to set the field differently depending on if its a field in a Ninja Document or not.
        if ($DocumentName) {
            $CustomField = Ninja-Property-Docs-Set -AttributeName $Name -AttributeValue $NinjaValue @DocumentationParams 2>&1
        }
        else {
            $CustomField = Ninja-Property-Set -Name $Name -Value $NinjaValue 2>&1
        }

        if ($CustomField.Exception) {
            throw $CustomField
        }
    }
}
process {

    $UacResults = [PSCustomObject]@{}
    # Loop through each value and get each value and add them to $UacResults as a property
    $Values | ForEach-Object {
        $Value = $_
        $Result = $null
        $Result = Get-ItemProperty -Path $Path -Name $Value -ErrorAction SilentlyContinue | Select-Object -ExpandProperty $Value
        if ($null -eq $Result) {
            switch ($Value) {
                'FilterAdministratorToken' { $Result = 0; break }
                'EnableUIADesktopToggle' { $Result = 0; break }
                'ConsentPromptBehaviorAdmin' { $Result = 5; break }
                'ConsentPromptBehaviorUser' { $Result = 3; break }
                'EnableInstallerDetection' { $Result = 0; break } # Assumes enterprise and not Home
                'ValidateAdminCodeSignatures' { $Result = 0; break }
                'EnableSecureUIAPaths' { $Result = 1; break }
                'EnableLUA' { $Result = 1; break }
                'PromptOnSecureDesktop' { $Result = 1; break }
                'EnableVirtualization' { $Result = 1; break }
                Default { $Result = 1 }
            }
        }
        $UacResults | Add-Member -MemberType NoteProperty -Name $Value -Value $Result
    }

    # Is UAC enabled or disabled
    if (
        $UacResults.ConsentPromptBehaviorAdmin -eq 5 -and
        $UacResults.ConsentPromptBehaviorUser -eq 3 -and
        $UacResults.EnableLUA -eq 1 -and
        $UacResults.FilterAdministratorToken -eq 0 -and
        $UacResults.EnableUIADesktopToggle -eq 0 -and
        $UacResults.ConsentPromptBehaviorAdmin -eq 5 -and
        $UacResults.ConsentPromptBehaviorUser -eq 3 -and
        # Enterprise
        (
            (
                (Get-CimInstance -ClassName Win32_OperatingSystem).Caption -notlike "*Home*" -and $UacResults.EnableInstallerDetection -eq 1
            ) -or
            (
                (Get-CimInstance -ClassName Win32_OperatingSystem).Caption -like "*Home*" -and $UacResults.EnableInstallerDetection -eq 0
            )
        ) -and
        $UacResults.ValidateAdminCodeSignatures -eq 0 -and
        $UacResults.EnableSecureUIAPaths -eq 1 -and
        $UacResults.EnableLUA -eq 1 -and
        $UacResults.PromptOnSecureDesktop -eq 1 -and
        $UacResults.EnableVirtualization -eq 1
    ) {
        "UAC Enabled with defaults." | Write-Host
    }
    elseif (
        $UacResults.EnableLUA -eq 0 -or
        $UacResults.ConsentPromptBehaviorAdmin -eq 0 -or
        $UacResults.PromptOnSecureDesktop -eq 0
    ) {
        "UAC Disabled." | Write-Host
    }

    # Get the UAC Level
    $UACLevel = if (
        $UacResults.EnableLUA -eq 0
    ) {
        0
    }
    elseif (
        $UacResults.ConsentPromptBehaviorAdmin -eq 5 -and
        $UacResults.PromptOnSecureDesktop -eq 0 -and
        $UacResults.EnableLUA -eq 1
    ) {
        1
    }
    elseif (
        $UacResults.ConsentPromptBehaviorAdmin -eq 5 -and
        $UacResults.PromptOnSecureDesktop -eq 1 -and
        $UacResults.EnableLUA -eq 1
    ) {
        2
    }
    elseif (
        $UacResults.ConsentPromptBehaviorAdmin -eq 2 -and
        $UacResults.PromptOnSecureDesktop -eq 1 -and
        $UacResults.EnableLUA -eq 1
    ) {
        3
    }

    # Get the Text version of the UAC Level
    $UACLevelText = switch ($UACLevel) {
        0 { "Never notify"; break }
        1 { "Notify me only (do not dim my desktop)"; break }
        2 { "Notify me only (default)"; break }
        3 { "Always notify"; break }
        Default { "Unknown"; break }
    }

    # Output the UAC Level
    "UAC Level: $UACLevel = $UACLevelText" | Write-Host

    # Output the UAC settings
    $UacResults | Out-String | Write-Host

    # When CustomField is used save the UAC Level to that custom field
    if ($CustomField) {
        try {
            Set-NinjaProperty -Name $CustomField -Value "$UACLevel = $UACLevelText" -ErrorAction Stop
        }
        catch {
            Write-Error "Failed to update Custom Field ($CustomField)"
            exit 2
        }
    }

    # Return and exit code of 0 if UAC is set to the default or higher, or 1 when not set to the default
    if ($UACLevel -ge 2) {
        exit 0
    }
    elseif ($UACLevel -lt 2) {
        exit 1
    }
    else {
        exit 1
    }
}
end {
    
    
    
}

 

Access over 300+ scripts in the NinjaOne Dojo

Get Access

Detailed breakdown

The script operates in several stages:

  • Parameter Initialization: It starts by defining a parameter CustomField which can be used to specify a custom field name for logging purposes.
  • Environment Setup: It checks for environmental variables and sets up registry paths and values related to UAC settings.
  • Function Definition: A function, Set-NinjaProperty, is defined to assist in updating NinjaOne’s custom fields. This feature is integral for MSPs using NinjaOne to manage client systems.
  • UAC Level Determination: The script then iterates through various UAC-related registry settings, comparing them with default or secure values to determine the UAC level of the system.
  • Output and Logging: It outputs the UAC level and settings to the console. If a CustomField is provided, the script logs the UAC level to this field.
  • Exit Code: Finally, the script concludes by returning an exit code based on the UAC level it has determined.

Potential use cases

Imagine an MSP managing a network of computers for a client. They could deploy this script across all machines to ensure that UAC settings are at their recommended levels, thereby preventing unauthorized changes that could compromise security.

Comparisons

Traditionally, UAC auditing might involve manual checks or less sophisticated scripts. This script offers a more automated, detailed, and integrated approach, particularly for environments managed through NinjaOne.

FAQs

  • Can this script run on any version of Windows?
    • It supports Windows 7, Windows Server 2012, and later versions.
  • Is it necessary to have administrative privileges to run this script?
    • Yes, it requires administrative rights to access and modify registry settings.
  • Can the script modify UAC settings?
    • While primarily designed for auditing, it can be extended to modify settings based on audit results.

Implications

Incorrect UAC settings can leave a system vulnerable to unauthorized access and potential malware installation. This script assists in maintaining optimal security configurations, thus mitigating such risks.

Recommendations

  • Regularly run the script to ensure continuous compliance with security standards.
  • Integrate the script into regular maintenance schedules for automated management.
  • Use the logging feature to maintain a record of UAC settings for audit trails.

Final thoughts

In the context of managing IT infrastructure, particularly when using NinjaOne, this PowerShell script is a valuable asset. It automates a critical aspect of security management, ensuring that UAC settings across an organization’s network remain at optimal levels for security and compliance. NinjaOne users can particularly benefit from the script’s integration capabilities, reinforcing the platform’s role as a comprehensive solution for managed IT services.

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