Demo ansehen×
×

Sehen Sie NinjaOne in Aktion!

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

Monitoring von Benutzeranmeldungen in Windows-Systemen mit PowerShell

Die wichtigsten Erkenntnisse

  • Automatisierte Benutzerüberwachung: Dieses PowerShell-Skript automatisiert die Überwachung von Benutzeranmeldungen auf Windows-Systemen.
  • Anpassbare Überprüfungen: Passen Sie das Skript so an, dass es nach bestimmten Benutzern oder jedem angemeldeten Benutzer sucht.
  • NinjaOne RMM-Integration: Integriert mit NinjaOne RMM für verbesserte Anpassung und Datenbeschaffung.
  • Operative Effizienz: Stellt sicher, dass die für die Anwendungsfunktionalität erforderlichen Benutzerkonten aktiv sind.
  • Verbesserung der Sicherheit: Hilft bei der Aufrechterhaltung der Sicherheit durch die Überwachung von autorisierten und nicht autorisierten Anmeldungen.
  • Flexibilität: Passt sich durch die Handhabung von Umgebungsvariablen an unterschiedliche Laufzeitumgebungen an.
  • Echtzeit-Warnungen: Bietet sofortige Warnungen basierend auf dem Anmeldestatus des Benutzers.
  • Kompatibilität: Unterstützt Windows 10 und Windows Server 2012 R2 aufwärts.
  • Einfache Integration: Kann in bestehende IT-Verwaltungstools integriert werden, um eine kohärente Systemüberwachung zu ermöglichen.
  • Unterstützung bei der Einhaltung der Vorschriften: Hilft bei der Einhaltung von Sicherheitsprotokollen durch die Verfolgung von Benutzeraktivitäten.

Hintergrund

Das bereitgestellte Skript ist ein PowerShell-Tool, das für IT-Experten und Managed Service Provider (MSPs ) entwickelt wurde, um Benutzeranmeldungen auf Windows-basierten Systemen zu überwachen. Ihre Bedeutung ergibt sich aus der Notwendigkeit, sicherzustellen, dass bestimmte Benutzerkonten aktiv sind, oder zu überprüfen, ob ein Benutzer angemeldet ist, insbesondere bei älteren Anwendungen, die authentifizierte Benutzersitzungen erfordern. Das Skript zeichnet sich durch seine Anpassungsmöglichkeiten und die Integration mit NinjaOne RMM, unserer Plattform für Fernüberwachung und -verwaltung, aus.

Das Skript:

<#
.SYNOPSIS
    Alert if no user is logged in, or if a specified user is not logged in. It can also accept a custom text field name to identify the user to check.
.DESCRIPTION
    Alert if no user is logged in, or if a specified user is not logged in. It can also accept a custom text field name to identify the user to check.
    
    Intended for legacy apps that are non-functional without an actual user account signed in.
.EXAMPLE
    (No Parameters)
    itAdmin alternateAdmin tuser is currently signed in!

PARAMETER: -CheckUser "itAdmin"
    Enter in the user you'd like to alert on. ex. to alert on user itAdmin use -CheckUser "itAdmin"
.EXAMPLE
    -CheckUser "itAdmin"
    itAdmin is currently signed in!

PARAMETER: -CustomFieldName "ReplaceMeWithAnyTextCustomField"
    The name of a text custom field to grab the CheckUser value from.
.EXAMPLE
    -CustomFieldName "ReplaceMeWithAnyTextCustomField"
    itAdmin is currently signed in!

.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2012 R2
    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()]
    [Switch]$ActiveOnly = [System.Convert]::ToBoolean($env:userMustBeActive),
    [Parameter()]
    [String]$CheckUser,
    [Parameter()]
    [String]$CustomFieldName
)

begin {
    # If script variables are used overwrite the existing variables.
    if ($env:userToCheckFor -and $env:userToCheckFor -notlike "null") { $CheckUser = $env:userToCheckFor }
    if ($env:retrieveUserFromCustomFieldName -and $env:retrieveUserFromCustomFieldName -notlike "null") { $CustomFieldName = $env:retrieveUserFromCustomFieldName }

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

        if($PSVersionTable.PSVersion.Major -lt 3){
            throw "PowerShell 3.0 or higher is required to retrieve data from custom fields. https://ninjarmm.zendesk.com/hc/en-us/articles/4405408656013"
        }

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

        # These two types require more information to parse.
        $NeedsOptions = "DropDown","MultiSelect"

        # Grabbing document values requires a slightly different command.
        if ($DocumentName) {
            # Secure fields are only readable when they're a device custom field
            if ($Type -Like "Secure") { throw "$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" }

            # 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.
            Write-Host "Retrieving value from Ninja Document..."
            $NinjaPropertyValue = Ninja-Property-Docs-Get -AttributeName $Name @DocumentationParams 2>&1

            # Certain fields require more information to parse.
            if ($NeedsOptions -contains $Type) {
                $NinjaPropertyOptions = Ninja-Property-Docs-Options -AttributeName $Name @DocumentationParams 2>&1
            }
        }
        else {
            # We'll redirect error output to the success stream to make it easier to error out if nothing was found or something else went wrong.
            $NinjaPropertyValue = Ninja-Property-Get -Name $Name 2>&1

            # Certain fields require more information to parse.
            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 ($NinjaPropertyValue.Exception) { throw $NinjaPropertyValue }
        if ($NinjaPropertyOptions.Exception) { throw $NinjaPropertyOptions }

        # This switch will compare the type given with the quoted string. If it matches, it'll parse it further; otherwise, the default option will be selected.
        switch ($Type) {
            "Attachment" {
                # Attachments come in a JSON format this will convert it into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Checkbox" {
                # Checkbox's come in as a string representing an integer. We'll need to cast that string into an integer and then convert it to a more traditional boolean.
                [System.Convert]::ToBoolean([int]$NinjaPropertyValue)
            }
            "Date or Date Time" {
                # In Ninja Date and Date/Time fields are in Unix Epoch time in the UTC timezone the below should convert it into local time as a datetime object.
                $UnixTimeStamp = $NinjaPropertyValue
                $UTC = (Get-Date "1970-01-01 00:00:00").AddSeconds($UnixTimeStamp)
                $TimeZone = [TimeZoneInfo]::Local
                [TimeZoneInfo]::ConvertTimeFromUtc($UTC, $TimeZone)
            }
            "Decimal" {
                # In ninja decimals are strings that represent a decimal this will cast it into a double data type.
                [double]$NinjaPropertyValue
            }
            "Device Dropdown" {
                # Device Drop-Downs Fields come in a JSON format this will convert it into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Device MultiSelect" {
                # Device Multi-Select Fields come in a JSON format this will convert it into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Dropdown" {
                # Drop-Down custom fields come in as a comma-separated list of GUIDs; we'll compare these with all the options and return just the option values selected instead of a GUID.
                $Options = $NinjaPropertyOptions -replace '=', ',' | ConvertFrom-Csv -Header "GUID", "Name"
                $Options | Where-Object { $_.GUID -eq $NinjaPropertyValue } | Select-Object -ExpandProperty Name
            }
            "Integer" {
                # Cast's the Ninja provided string into an integer.
                [int]$NinjaPropertyValue
            }
            "MultiSelect" {
                # Multi-Select custom fields come in as a comma-separated list of GUID's we'll compare these with all the options and return just the option values selected instead of a guid.
                $Options = $NinjaPropertyOptions -replace '=', ',' | ConvertFrom-Csv -Header "GUID", "Name"
                $Selection = ($NinjaPropertyValue -split ',').trim()

                foreach ($Item in $Selection) {
                    $Options | Where-Object { $_.GUID -eq $Item } | Select-Object -ExpandProperty Name
                }
            }
            "Organization Dropdown" {
                # Turns the Ninja provided JSON into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Organization Location Dropdown" {
                # Turns the Ninja provided JSON into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Organization Location MultiSelect" {
                # Turns the Ninja provided JSON into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Organization MultiSelect" {
                # Turns the Ninja provided JSON into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Time" {
                # Time fields are given as a number of seconds starting from midnight. This will convert it into a datetime object.
                $Seconds = $NinjaPropertyValue
                $UTC = ([timespan]::fromseconds($Seconds)).ToString("hh\:mm\:ss")
                $TimeZone = [TimeZoneInfo]::Local
                $ConvertedTime = [TimeZoneInfo]::ConvertTimeFromUtc($UTC, $TimeZone)

                Get-Date $ConvertedTime -DisplayHint Time
            }
            default {
                # If no type was given or not one that matches the above types just output what we retrieved.
                $NinjaPropertyValue
            }
        }
    }

    function Get-User {
        $quser = quser.exe
        $quser -replace '\s{2,}', ',' -replace '>' | ConvertFrom-Csv
    }

}process {

    # If a custom field name is provided grab the text and overwrite the $CheckUser variable with it.
    if ($CustomFieldName) { 
        if (-not ($CheckUser)) {
            try{
                $CheckUser = Get-NinjaProperty -Name $CustomFieldName
            }catch{
                Write-Warning "$($_.ToString())"
            }

            if(-not $CheckUser){
                Write-Warning "The custom field $CustomFieldName was empty!" 
            }
        }
    }

    if($CheckUser){
        Write-Host "Checking for $CheckUser."
    }else{
        Write-Host "Checking if any user is logged in."
    }

    # This will work whether or not your looking for any user to be logged in ($CheckUser = $null) or a specific one.
    $LoggedInUsers = Get-User
    if ($ActiveOnly) {
        $Test = $LoggedInUsers | Where-Object { $_.USERNAME -match $CheckUser } | Where-Object { $_.STATE -like "Active" }
    }
    else {
        $Test = $LoggedInUsers | Where-Object { $_.USERNAME -match $CheckUser } 
    }

    # If we didn't find the user or users we were looking for error out and exit 1
    if (!$Test) {
        Write-Error "The user(s) you are checking for is not currently logged in!"
        $LoggedInUsers | Format-Table USERNAME, STATE, "LOGON TIME", SESSIONNAME | Out-String | Write-Host
        exit 1
    }
    else {
        # Otherwise exit 0
        Write-Host "$($LoggedInUsers.USERNAME) is currently signed in!"
        $LoggedInUsers | Format-Table USERNAME, STATE, "LOGON TIME", SESSIONNAME | Out-String | Write-Host
        exit 0
    }
    
}end {
    
    
    
}

 

Zugriff auf über 300 Skripte im NinjaOne Dojo

Zugang erhalten

Detaillierte Aufschlüsselung

Das Skript arbeitet in mehreren Stufen:

  • Initialisierung: Sie beginnt mit der Einrichtung von Parametern, die ihr Verhalten steuern, wie z. B. die Überprüfung nur aktiver Benutzer oder die Konzentration auf einen bestimmten Benutzer.
  • Handhabung von Umgebungsvariablen: Es überprüft Umgebungsvariablen, die möglicherweise seine Parameter überschreiben könnten, um Anpassungsfähigkeit in verschiedenen Laufzeitumgebungen zu gewährleisten.
  • Abfrage von benutzerdefinierten Feldern: Das Skript kann Benutzerinformationen aus benutzerdefinierten Feldern abrufen, was Flexibilität beim Abrufen von Anmeldedaten ermöglicht.
  • Benutzeranmeldedatenabruf : Durch die Verwendung des Befehls quser ruft es die Liste der angemeldeten Benutzer:innen ab, eine Kernfunktionalität des Skripts.
  • Benutzerprüfung und -warnung: Je nach den festgelegten Parametern überprüft das Skript entweder nach jedem angemeldeten Benutzer oder einem bestimmten Benutzer und gibt entsprechende Warnungen aus.

Mögliche Anwendungsfälle

Stellen Sie sich einen IT-Administrator vor, der für ein Netzwerk verantwortlich ist, in dem für bestimmte Anwendungen ein Admin-Benutzer ständig angemeldet sein muss. Mit diesem Skript können sie automatische Überprüfungen einrichten, um sicherzustellen, dass die erforderlichen Benutzerkonten aktiv sind, und so die Funktionalität der Anwendung und die Systemsicherheit aufrechterhalten.

Vergleiche

Herkömmliche Methoden zur Überwachung der Benutzeranmeldung beinhalten manuelle Prüfungen oder einfache Skripte ohne Anpassungsmöglichkeiten. Dieses PowerShell-Skript übertrifft diese Methoden mit seiner Integration in NinjaOne RMM, seiner Anpassungsfähigkeit und seinen automatischen Alarmierungsfunktionen.

FAQs

F: Wie wird die Sicherheit durch dieses Skript verbessert?
A: Indem sichergestellt wird, dass die erforderlichen Benutzerkonten aktiv sind und nicht autorisierte Anmeldungen überwacht werden.

F: Kann es für Nicht-Administratoren angepasst werden?
A: Natürlich kann das Skript so angepasst werden, dass es jedes Benutzerkonto überwacht.

F: Ist es mit allen Windows-Versionen kompatibel?
A: Es unterstützt Windows 10 und Windows Server 2012 R2 und höher.

Auswirkungen

Die Fähigkeit des Skripts, Benutzeranmeldungen zu überwachen, ist für die Aufrechterhaltung von Sicherheitsprotokollen, die Einhaltung von Vorschriften und die Verhinderung von unbefugtem Zugriff unerlässlich. Es hilft auch bei der Fehlersuche und der betrieblichen Wartung, indem es Benutzeranmeldedaten in Echtzeit bereitstellt.

Empfehlungen

  • Aktualisieren Sie das Skript regelmäßig, um mit Systemaktualisierungen Schritt zu halten.
  • Passen Sie die Skriptparameter an die spezifischen Anforderungen der IT-Umgebung an.
  • Integrieren Sie das Skript in bestehende IT-Verwaltungstools, um einen kohärenten Überwachungsansatz zu erhalten.

Abschließende Überlegungen

Die Einbindung dieses PowerShell-Skripts in Ihre IT-Infrastruktur, insbesondere in Kombination mit NinjaOne, verbessert Ihre Möglichkeiten zur effektiven Überwachung von Benutzeranmeldungen. Die Plattform von NinjaOne bietet eine zusätzliche Verwaltungs- und Sicherheitsebene, die das Skript zu einem unschätzbaren Bestandteil einer umfassenden IT-Managementstrategie macht.

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

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