How to Retrieve the Current Device Description with PowerShell

Device metadata plays a critical role in IT asset management. One often-overlooked piece of information is the device description, which can contain valuable contextual data—such as location, role, or assigned user—that enhances visibility across environments.

For IT professionals and managed service providers (MSPs), ensuring this information is not only accessible but also integrated into their management platforms can drive more efficient operations. This script is designed to retrieve the current device description with PowerShell and to optionally store it as a custom field within NinjaOne, providing automation-friendly insights for better documentation and asset tracking.

Background

The script fulfills a straightforward but impactful objective: retrieve the Windows device description and, if specified, save it to a NinjaOne custom field. While the Windows device description is rarely updated manually, it can provide quick insights into a machine’s intended role or configuration. Centralizing this data in NinjaOne, especially through automation, reduces the time IT teams spend jumping between tools or querying remote systems manually.

IT administrators often juggle dozens, if not hundreds, of devices. Whether during onboarding, audits, or troubleshooting, having key descriptive data readily available in an RMM platform like NinjaOne can streamline workflows and reduce errors. This script fits squarely into a broader automation strategy that prioritizes context-aware infrastructure.

The Script:

<#
.SYNOPSIS
    Retrieves the current device description and optionally saves it to a custom field.
.DESCRIPTION
    Retrieves the current device description and optionally saves it to a custom field.
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).
.EXAMPLE
    -CustomField "text"
    
    Current device description: 'Kitchen Computer'
    Attempting to set custom field 'text'.
    Successfully set custom field 'text'!

PARAMETER: -CustomField "ExampleInput"
    Optionally specify the name of a custom field you would like to save the results to.

.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2012 R2
    Release Notes: Initial Release
#>

[CmdletBinding()]
param (
    [Parameter()]
    [String]$CustomField
)

begin {
    if ($env:nameOfCustomField -and $env:nameOfCustomField -notlike "null") { $CustomField = $env:nameOfCustomField }

    # PowerShell 3 or higher is required for custom field functionality
    if ($PSVersionTable.PSVersion.Major -lt 3 -and $CustomField) {
        Write-Host -Object "[Error] Setting custom fields requires powershell version 3 or higher."
        Write-Host -Object "https://ninjarmm.zendesk.com/hc/en-us/articles/4405408656013-Custom-Fields-and-Documentation-CLI-and-Scripting"
        exit 1
    }

    function Set-NinjaProperty {
        [CmdletBinding()]
        Param(
            [Parameter(Mandatory = $True)]
            [String]$Name,
            [Parameter()]
            [String]$Type,
            [Parameter(Mandatory = $True, ValueFromPipeline = $True)]
            $Value,
            [Parameter()]
            [String]$DocumentName
        )
        
        $Characters = $Value | Out-String | Measure-Object -Character | Select-Object -ExpandProperty Characters
        if ($Characters -ge 200000) {
            throw [System.ArgumentOutOfRangeException]::New("Character limit exceeded: the value is greater than or equal to 200,000 characters.")
        }
            
        # If requested to set the field value for a Ninja document, specify it here.
        $DocumentationParams = @{}
        if ($DocumentName) { $DocumentationParams["DocumentName"] = $DocumentName }
            
        # This is a list of valid fields that can be set. If no type is specified, assume that the input does not need to be changed.
        $ValidFields = "Attachment", "Checkbox", "Date", "Date or Date Time", "Decimal", "Dropdown", "Email", "Integer", "IP Address", "MultiLine", "MultiSelect", "Phone", "Secure", "Text", "Time", "URL", "WYSIWYG"
        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 field below requires additional information to set.
        $NeedsOptions = "Dropdown"
        if ($DocumentName) {
            if ($NeedsOptions -contains $Type) {
                # Redirect error output to the success stream to handle errors more easily if nothing is found or something else goes 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 an error is received with an exception property, exit the function with that error information.
        if ($NinjaPropertyOptions.Exception) { throw $NinjaPropertyOptions }
            
        # The types below require values not typically given to be set. The code below will convert whatever we're given into a format ninjarmm-cli supports.
        switch ($Type) {
            "Checkbox" {
                # Although it's highly likely we were given a value like "True" or a boolean data type, it's better to be safe than sorry.
                $NinjaValue = [System.Convert]::ToBoolean($Value)
            }
            "Date or Date Time" {
                # Ninjarmm-cli expects the GUID of the option to be selected. Therefore, match the given value with a GUID.
                $Date = (Get-Date $Value).ToUniversalTime()
                $TimeSpan = New-TimeSpan (Get-Date "1970-01-01 00:00:00") $Date
                $NinjaValue = $TimeSpan.TotalSeconds
            }
            "Dropdown" {
                # Ninjarmm-cli expects the GUID of the option we're trying to select, so match 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 [System.ArgumentOutOfRangeException]::New("Value is not present in dropdown options.")
                }
            
                $NinjaValue = $Selection
            }
            default {
                # All the other types shouldn't require additional work on the input.
                $NinjaValue = $Value
            }
        }
            
        # Set the field differently depending on whether it's a field in a Ninja Document or not.
        if ($DocumentName) {
            $CustomField = Ninja-Property-Docs-Set -AttributeName $Name -AttributeValue $NinjaValue @DocumentationParams 2>&1
        }
        else {
            $CustomField = $NinjaValue | Ninja-Property-Set-Piped -Name $Name 2>&1
        }
            
        if ($CustomField.Exception) {
            throw $CustomField
        }
    }
    
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    if (!$ExitCode) {
        $ExitCode = 0
    }
}
process {
    # Check if the script is being run with elevated (administrator) privileges
    if (!(Test-IsElevated)) {
        Write-Host -Object "[Error] Access denied. Please run with administrator privileges."
        exit 1
    }

    try {
        # Determine the PowerShell version and get the operating system description accordingly
        if ($PSVersionTable.PSVersion.Major -lt 5) {
            # Use Get-WmiObject for PowerShell versions less than 5
            $Description = $(Get-WmiObject -Class Win32_OperatingSystem -ErrorAction Stop).Description
        }
        else {
            # Use Get-CimInstance for PowerShell version 5 or greater
            $Description = $(Get-CimInstance -Class Win32_OperatingSystem -ErrorAction Stop).Description
        }

        # Trim any leading or trailing whitespace from the description
        if ($Description) {
            $Description = $Description.Trim()
        }
    }
    catch {
        # Handle any errors that occur while retrieving the device description
        Write-Host -Object "[Error] Failed to retrieve current device description."
        Write-Host -Object "[Error] $($_.Exception.Message)"
        exit 1
    }

    # Check if the description is empty or not
    if (!$Description) {
        Write-Host -Object "[Alert] No device description is currently set."
        $CustomFieldValue = "No device description is currently set."
    }
    else {
        Write-Host -Object "Current device description: '$Description'"
        $CustomFieldValue = $Description
    }

    # If a custom field is specified, attempt to set its value
    if ($CustomField) {
        try {
            Write-Host "Attempting to set custom field '$CustomField'."
            Set-NinjaProperty -Name $CustomField -Value $CustomFieldValue
            Write-Host "Successfully set custom field '$CustomField'!"
        }
        catch {
            Write-Host -Object "[Error] Failed to set custom field '$CustomField'"
            Write-Host "[Error] $($_.Exception.Message)"
            exit 1
        }
    }

    exit $ExitCode
}
end {
    
    
    
}

 

Detailed Breakdown

The script begins with a parameter declaration, allowing the user to pass an optional -CustomField argument to define where the device description should be saved in NinjaOne.

Key Functional Areas:

  1. Environment Variable Override
    It checks if the environment variable nameOfCustomField is set, which can override the -CustomField parameter—making the script adaptable in automated pipelines.
  2. PowerShell Version Check
    Custom field functionality requires PowerShell version 3 or above. If a lower version is detected, the script exits early with a helpful message and documentation link.
  3. Custom Function: Set-NinjaProperty
    This versatile function handles the logic for updating NinjaOne custom fields, with built-in support for data types such as Dropdown, Checkbox, and DateTime. It validates inputs, handles formatting quirks, and uses NinjaOne’s CLI to commit the update. Exception handling ensures that invalid field values or API errors do not go unnoticed.
  4. Elevation Check
    The script confirms it is running with administrative privileges using the Test-IsElevated function, a best practice when accessing WMI or CIM classes.
  5. Retrieve the Description
    Depending on PowerShell version:

    • PowerShell < 5: Uses Get-WmiObject
    • PowerShell ≥ 5: Uses Get-CimInstance
      The retrieved description is trimmed and stored in a variable.
  6. Set the Custom Field (If Requested)
    If the description exists and a custom field is specified, the value is passed to Set-NinjaProperty. Otherwise, the script logs that no description is set.

Potential Use Cases

Consider a scenario where an MSP is onboarding a batch of 150 Windows endpoints across several office locations. Each machine has a device description indicating its intended location (e.g., “NYC-Conference-Room”). By deploying this script via NinjaOne’s scripting module and tying the result to a custom field like “Location Tag,” the MSP can quickly view and sort machines based on their roles and locations—without needing to log into each one. This supports quicker troubleshooting, smarter alert routing, and easier reporting.

Comparisons

Traditionally, retrieving the device description might involve logging into each endpoint and manually checking system properties or writing a one-off WMI query. Some administrators may use Group Policy or configuration management tools to enforce naming conventions, but those rarely synchronize with RMM platforms like NinjaOne. By comparison, this script offers:

  • Automation – Easily deployed through RMM scripting modules.
  • Documentation Integration – Seamlessly updates NinjaOne custom fields.
  • Scalability – Ideal for large or distributed environments.

FAQs

Q: What if the device has no description set?

A: The script will return a message indicating that no description is set and populate the custom field (if defined) with a placeholder message.

Q: What are NinjaOne custom fields?

A: These are user-defined metadata fields that allow documentation and automation inside NinjaOne. They support various data types like text, dropdowns, and secure values.

Q: Can this script update other system information?

A: While this version focuses solely on the device description, the Set-NinjaProperty function is modular and can be reused to update other fields with minor modification.

Q: Will this work on older systems?

A: The script supports Windows 10 and Windows Server 2012 R2 or later. PowerShell version 3 or higher is required to update custom fields.

Implications

Ensuring that contextual metadata like device descriptions are centrally available enhances visibility and responsiveness. Inconsistent or missing device descriptions can hinder audits, delay support tickets, and even lead to misconfigurations. Automating the synchronization of this metadata with NinjaOne also lays the groundwork for more sophisticated asset classification, compliance reporting, and alert handling—all while minimizing administrative overhead.

Recommendations

  • Run the script as administrator to ensure reliable access to WMI/CIM.
  • Define consistent device description standards across your organization (e.g., Location-Role).
  • Pair this script with onboarding workflows so every newly deployed device is automatically documented.
  • Use NinjaOne’s custom field constraints to ensure accurate and meaningful data entry.
  • Test in a staging environment before wide deployment to validate field mappings and data formats.

Final Thoughts

For IT professionals and MSPs managing diverse fleets of Windows devices, context is key. Automating the retrieval and documentation of device descriptions with PowerShell not only improves visibility but also enables smarter, faster decision-making. NinjaOne’s custom fields act as a bridge between raw device data and actionable insight. By integrating scripts like this into your workflow, you create a robust, scalable, and reliable IT documentation ecosystem—one that grows as intelligently as your infrastructure.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service delivery 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

×

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