Automate Setting Custom Field Values in IT Systems with PowerShell

Key takeaways

  • Automation with PowerShell: The script leverages PowerShell for efficient data management in IT systems, particularly in MSP environments.
  • Custom field management: It is designed to set custom field values in NinjaOne, demonstrating adaptability to specific IT tools.
  • Administrative privileges: Execution requires local admin rights, emphasizing the need for security in system-level operations.
  • Field type handling: Includes logic for handling various data types like ‘Checkbox’, ‘Date’, and ‘Dropdown’, ensuring accurate data entry.
  • Error management: Incorporates error handling to catch and report issues, enhancing reliability.
  • Efficiency over manual methods: Offers a more efficient alternative to manual data updates, reducing human error and saving time.
  • Security considerations: Implies the need for strict access control and auditing to prevent misuse and data breaches.
  • Power of automation in IT: Highlights the transformative impact of automation in IT tasks, improving accuracy and operational efficiency.

Customization in IT systems is pivotal for efficiency and accuracy in operations. This holds especially true in Managed Service Providers (MSPs) and IT departments where scripts, like the one detailed here, are used to set custom field values. By leveraging PowerShell, a powerful scripting language, IT professionals can automate and simplify complex tasks, leading to optimized performance and reduced human error. 

Background

The provided script is a classic example of how PowerShell can interact with specific IT management tools – in this case, NinjaOne (a popular remote monitoring and management software). The ability to programmatically set custom field values is crucial for MSPs and IT administrators who need to handle vast amounts of data across numerous devices and documents. This script is a tool for streamlining data management and ensuring consistency across an IT infrastructure.

The script:

#Requires -Version 4

<#
.SYNOPSIS
    This is an example script for setting a custom field value. Specifying a type is recommended but not required.
.DESCRIPTION
    This is an example script for setting a custom field value. Specifying a type is recommended but not required.
.EXAMPLE
    -CustomFieldName "text" -Value "Even More Text"
    
    Setting Custom Field 'text' with value 'Even More Text'....
    Success!

PARAMETER: -CustomFieldName "NameOfAcustomFieldToSet"
    The name of a custom field that you would like to set.

PARAMETER: -CustomFieldType "ReplaceMeWithFieldType"
    The type of custom field you are trying to set.
    Valid options are: "Text", "Checkbox", "Date", "Date And Time", "Decimal", "Dropdown", "Email", "Integer", "IP Address", "MultiLine", "Phone", "Secure", "URL"

PARAMETER: -NinjaDocumentName "Replace Me With A Ninja Document Name"
    Name of a Ninja Document you would like to retrieve these field values from. Leave blank to retrieve values from device custom fields.

PARAMETER: -Value "ReplaceMe"
    The value you would like to set for the custom field.
    
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10, Server 2012 R2
    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]$CustomFieldName,
    [Parameter()]
    [String]$CustomFieldType,
    [Parameter()]
    [String]$NinjaDocumentName,
    [Parameter()]
    [String]$Value
)

begin {
    # Grab parameters from dynamic script variables.
    if ($env:customFieldName -and $env:customFieldName -notlike "null") { $CustomFieldName = $env:customFieldName }
    if ($env:customFieldType -and $env:customFieldType -notlike "null") { $CustomFieldType = $env:customFieldType }
    if ($env:ninjaDocumentName -and $env:ninjaDocumentName -notlike "null") { $NinjaDocumentName = $env:ninjaDocumentName }
    if ($env:value -and $env:value -notlike "null") { $Value = $env:value }

    # A custom field name is required.
    if (-not $CustomFieldName) {
        Write-Error "No custom field was specified!"
        exit 1
    }

    # If the custom field type specified is a date or date and time, change it to "Date or Date Time" to be used by the function.
    if ($CustomFieldType -eq "Date" -or $CustomFieldType -eq "Date And Time") {
        $CustomFieldType = "Date or Date Time"
    }

    # Local Admin rights are required to read or write custom fields.
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    # 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 {
    # If this script doesn't have Local Admin rights, error out.
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    
    # These are the three default mandatory parameters. We'll 'splat' them later.
    $NinjaPropertyParams = @{
        Name        = $CustomFieldName
        Value       = $Value
        ErrorAction = "Stop"
    }

    # If either of the optional options were given, add it to the parameter list to be 'splatted' later.
    if ($CustomFieldType) { $NinjaPropertyParams["Type"] = $CustomFieldType }
    if ($NinjaDocumentName) { $NinjaPropertyParams["DocumentName"] = $NinjaDocumentName }

    # Log that we are about to attempt setting a custom field.
    Write-Host "Setting Custom Field '$CustomFieldName' with value '$Value'...."

    # Set a custom field using our function with the 'splatted' options.
    try {
        Set-NinjaProperty @NinjaPropertyParams
    }
    catch {
        # If we ran into some sort of error we'll output it here.
        Write-Error -Message $_.ToString() -Category InvalidOperation -Exception (New-Object System.Exception)
        exit 1
    }

    Write-Host "Success!"
}
end {

 

Access over 300+ scripts in the NinjaOne Dojo

Get Access

Detailed breakdown

  • Script structure: The script begins with a synopsis and description, followed by parameters for custom field names, types, document names, and values.
  • Initialization: In the ‘begin’ block, it captures and validates the provided parameters, ensuring a custom field name is specified. If ‘Date’ or ‘Date and Time’ fields are selected, it adjusts the format to ‘Date or Date Time’.
  • Admin rights check: The script includes a function to verify if it’s running with local administrative privileges, an essential requirement for modifying system settings.
  • Setting custom fields: The core function, Set-NinjaProperty, takes various parameters and handles different field types, including special handling for ‘Checkbox’, ‘Date or Date Time’, and ‘Dropdown’ fields.
  • Error handling: In the ‘process’ block, the script uses a try-catch statement to manage errors during the field setting operation, ensuring that any issues are caught and reported clearly.
  • Execution flow: The script wraps up by applying the changes and displaying a success message.

Potential use cases

Consider an MSP managing client’s IT infrastructure. They need to update compliance status across numerous devices. Using this script, they can automate the process, ensuring that each device’s custom field is updated accurately and efficiently, thus saving time and reducing errors.

Comparisons

Traditional methods might involve manual updates through a GUI, prone to human error and time-consuming. This script, however, automates the process, providing a faster, more reliable, and scalable solution.

FAQs

  • How does this script handle different types of fields?
    • The script includes specific logic to handle various field types, ensuring correct data formatting.
  • Is it necessary to have administrative rights to run this script?
    • Yes, local administrative rights are required for modifying system settings.
  • Can this script handle errors during execution?
    • Yes, it uses try-catch blocks to catch and report errors effectively.

Implications

While this script enhances efficiency, it also carries implications for IT security. Unauthorized use could lead to incorrect data handling or breaches. Thus, strict access controls and auditing are recommended.

Recommendations

  • Validate input: Ensure all inputs to the script are validated to avoid errors.
  • Manage permissions: Restrict script usage to authorized personnel only.
  • Audit usage: Keep logs of script execution for accountability.

Final thoughts

In an era where data is king, efficient and accurate data management is crucial. NinjaOne, combined with PowerShell scripting, offers a robust solution for MSPs and IT professionals. This script exemplifies how automation can transform mundane tasks into efficient processes, fostering a more resilient and responsive 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

×

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