Automatisieren der Einstellung von benutzerdefinierten Feldwerten in IT-Systemen mit PowerShell

Die wichtigsten Erkenntnisse

  • Automatisierung mit PowerShell: Das Skript nutzt die PowerShell für eine effiziente Datenverwaltung in IT-Systemen, insbesondere in MSP-Umgebungen.
  • Verwaltung benutzerdefinierter Felder: Es wurde entwickelt, um benutzerdefinierte Feldwerte in NinjaOne zu setzen, was die Anpassungsfähigkeit an spezifische IT-Tools demonstriert.
  • Administrative Privilegien: Die Ausführung erfordert lokale Administratorrechte, was die Notwendigkeit von Sicherheit bei Operationen auf Systemebene unterstreicht.
  • Handhabung des Feldtyps: Enthält eine Logik für die Verarbeitung verschiedener Datentypen wie ‚Checkbox‘, ‚Datum‘ und ‚Dropdown‘, die eine genaue Dateneingabe gewährleistet.
  • Fehlermanagement: Enthält eine Fehlerbehandlung, um Probleme zu erkennen und zu melden, was die Zuverlässigkeit erhöht.
  • Effizienter als manuelle Methoden: Bietet eine effizientere Alternative zur manuellen Datenaktualisierung, reduziert menschliche Fehler und spart Zeit.
  • Sicherheitserwägungen: Dies impliziert die Notwendigkeit einer strengen Zugangskontrolle und Prüfung, um Missbrauch und Datenschutzverletzungen zu verhindern.
  • DieMacht der Automatisierung in der IT: Hebt die transformative Wirkung der Automatisierung von IT-Aufgaben hervor, die die Genauigkeit und betriebliche Effizienz verbessert.

Die Anpassung von IT-Systemen ist für die Effizienz und Genauigkeit der Abläufe von zentraler Bedeutung. Dies gilt insbesondere für Managed Service Provider (MSPs) und IT-Abteilungen, in denen Skripte, wie das hier beschriebene, verwendet werden, um benutzerdefinierte Feldwerte festzulegen. Durch den Einsatz von PowerShell, einer leistungsstarken Skriptsprache, können IT-Experten komplexe Aufgaben automatisieren und vereinfachen, was zu einer optimierten Leistung und weniger menschlichen Fehlern führt. 

Hintergrund

Das bereitgestellte Skript ist ein klassisches Beispiel dafür, wie PowerShell mit bestimmten IT-Verwaltungstools interagieren kann – in diesem Fall mit NinjaOne (einer beliebten Software für Fernüberwachung und -verwaltung). Die Möglichkeit, benutzerdefinierte Feldwerte programmatisch festzulegen, ist für MSPs und IT-Administratoren, die große Datenmengen über zahlreiche Geräte und Dokumente hinweg verwalten müssen, von entscheidender Bedeutung. Dieses Skript ist ein Werkzeug zur Rationalisierung der Datenverwaltung und zur Gewährleistung der Konsistenz innerhalb einer IT-Infrastruktur.

Das Skript:

#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 {

 

Zugriff auf über 300 Skripte im NinjaOne Dojo

Zugang erhalten

Detaillierte Aufschlüsselung

  • Struktur des Drehbuchs: Das Skript beginnt mit einer Zusammenfassung und Beschreibung, gefolgt von Parametern für benutzerdefinierte Feldnamen, Typen, Dokumentnamen und Werte.
  • Initialisierung: Im „begin“-Block werden die übergebenen Parameter erfasst und validiert, um sicherzustellen, dass ein benutzerdefinierter Feldname angegeben ist. Wenn die Felder „Datum“ oder „Datum und Uhrzeit“ ausgewählt sind, wird das Format auf „Datum oder Datumszeit“ eingestellt.
  • Überprüfung der Administratorrechte: Das Skript enthält eine Funktion, mit der überprüft wird, ob es mit lokalen Administratorrechten ausgeführt wird, eine wesentliche Voraussetzung für die Änderung von Systemeinstellungen.
  • Benutzerdefinierte Felder einstellen: Die Kernfunktion Set-NinjaProperty nimmt verschiedene Parameter entgegen und behandelt verschiedene Feldtypen, einschließlich der speziellen Behandlung von ‚Checkbox‘-, ‚Date or Date Time‘- und ‚Dropdown‘-Feldern.
  • Fehlerbehandlung: Im „process“-Block verwendet das Skript eine „try-catch“-Anweisung, um Fehler während des Feldeinstellungsvorgangs zu verwalten und sicherzustellen, dass alle Probleme abgefangen und eindeutig gemeldet werden.
  • Ausführungsablauf: Das Skript endet mit der Übernahme der Änderungen und der Anzeige einer Erfolgsmeldung.

Mögliche Anwendungsfälle

Nehmen wir an, ein MSP verwaltet die IT-Infrastruktur des Kunden. Sie müssen den Konformitätsstatus über zahlreiche Geräte hinweg aktualisieren. Mit diesem Skript können sie den Prozess automatisieren und sicherstellen, dass das benutzerdefinierte Feld jedes Geräts genau und effizient aktualisiert wird, was Zeit spart und Fehler reduziert.

Vergleiche

Herkömmliche Methoden können manuelle Aktualisierungen über eine grafische Benutzeroberfläche beinhalten, die anfällig für menschliche Fehler und zeitaufwändig sind. Dieses Skript automatisiert jedoch den Prozess und bietet eine schnellere, zuverlässigere und skalierbare Lösung.

FAQs

  • Wie behandelt dieses Skript verschiedene Arten von Feldern?
    • Das Skript enthält eine spezielle Logik zur Behandlung verschiedener Feldtypen, die eine korrekte Datenformatierung gewährleistet.
  • Sind für die Ausführung dieses Skripts Administratorrechte erforderlich?
    • Ja, zum Ändern der Systemeinstellungen sind lokale Administratorrechte erforderlich.
  • Kann dieses Skript mit Fehlern während der Ausführung umgehen?
    • Ja, es verwendet try-catch-Blöcke, um Fehler effektiv abzufangen und zu melden.

Auswirkungen

Dieses Skript erhöht zwar die Effizienz, hat aber auch Auswirkungen auf die IT-Sicherheit. Eine unbefugte Nutzung könnte zu einer falschen Datenverarbeitung oder zu Verstößen führen. Daher werden strenge Zugangskontrollen und Audits empfohlen.

Empfehlungen

  • Eingabe validieren: Stellen Sie sicher, dass alle Eingaben in das Skript validiert werden, um Fehler zu vermeiden.
  • Verwalten Sie Berechtigungen: Beschränken Sie die Verwendung von Skripten auf autorisiertes Personal.
  • Audit-Verwendung: Protokolliert die Ausführung des Skripts zur Nachverfolgbarkeit.

Abschließende Überlegungen

In einer Zeit, in der Daten den Ton angeben, ist eine effiziente und präzise Datenverwaltung entscheidend. NinjaOne, kombiniert mit PowerShell-Skripten, bietet eine robuste Lösung für MSPs und IT-Experten. Dieses Skript veranschaulicht, wie Automatisierung gewöhnliche Aufgaben in effiziente Prozesse umwandeln kann, was eine belastbarere und reaktionsfähigere IT-Infrastruktur fördert. 

Nächste Schritte

Der Aufbau eines effizienten und effektiven IT-Teams erfordert eine zentralisierte Lösung, die als vereintes Tool für die Bereitstellung von Dienstleistungen fungiert. NinjaOne ermöglicht es IT-Teams, all ihre Geräte zu überwachen, verwalten, sichern und zu unterstützen, unabhängig von ihrem Ort und komplexer Infrastruktur vor Ort.

Erfahren Sie mehr über NinjaOne Endpoint Management schauen Sie sich eine Live-Tour an oder starten Sie Ihre kostenlose Testversion der NinjaOne Plattform.

Kategorien:

Das könnte Sie auch interessieren

Demo ansehen×
×

Sehen Sie NinjaOne in Aktion!

Mit dem Absenden dieses Formulars akzeptiere ich die Datenschutzerklärung von NinjaOne.

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