Demo ansehen×
×

Sehen Sie NinjaOne in Aktion!

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

Verwenden von PowerShell zum Abrufen des Gerätestandorts mit Google GeoLocation API

Wichtigste Erkenntnisse

  • Das Skript ruft den geografischen Standort eines Geräts mithilfe der Google GeoLocation API ab.
  • Es dient dazu, die benutzerdefinierten Felder von NinjaOne mit Standortdaten zu aktualisieren.
  • Das Skript erfordert eine aktive Internetverbindung und ist für Windows 10-Geräte optimiert.
  • Die Google GeoLocation API bietet im Vergleich zu anderen Methoden eine höhere Genauigkeit und eine breitere Abdeckung.
  • Die Verwendung des Skripts zur Standortverfolgung wirft ethische und datenschutzrechtliche Bedenken auf.
  • Um Verletzungen der Privatsphäre zu vermeiden, müssen vor dem Einsatz dieses Tools explizite Genehmigungen erteilt werden.
  • Es ist wichtig, die Tarifgrenzen und die damit verbundenen Kosten für die Google-API zu kennen.
  • NinjaOne bietet in Verbindung mit solchen Skripten robuste Funktionen für den IT-Betrieb und die Anlagenverwaltung.

Im vernetzten IT-Ökosystem von heute ist eine der wertvollsten Informationen der „Standort“. Die Möglichkeit, den geografischen Standort von Geräten zu verfolgen, kann sich bei vielen IT-Vorgängen als entscheidend erweisen, von der Anlagenverwaltung bis zur Sicherheitsüberwachung. In diesem Blogbeitrag wird ein PowerShell-Skript vorgestellt, mit dem IT-Experten und MSPs (Managed Service Provider) den Standort eines Windows-Geräts ermitteln und mit Hilfe der benutzerdefinierten Felder von NinjaOne speichern können.

Hintergrund

Das Skript im Fokus aktualisiert benutzerdefinierte Felder mit den geografischen Koordinaten und der Adresse eines Geräts unter Verwendung der Google GeoLocation API. Für IT-Fachleute und MSPs ist es von grundlegender Bedeutung, den physischen Standort eines Geräts zu kennen. Ob es darum geht, gestohlene Geräte aufzuspüren, Geräte zu überprüfen oder die geografische Verteilung von IT-Ressourcen zu verifizieren, die Anwendung eines solchen Skripts kann vielfältig und tiefgreifend sein.

Das Skript

#Requires -Version 5.1

<#
.SYNOPSIS
    Updates Custom Fields with the location of a device based on the Google GeoLocation API.
.DESCRIPTION
    Updates Custom Fields with the location of a device based on the Google GeoLocation API.

    The CustomFieldName parameter can be used to specify which custom field to save the Latitude and Longitude coordinates to.
    The AddressCustomFieldName parameter can be used to specify which custom field to save the address to.

    This script requires a custom field to save location data in NinjaRMM.
    The default for CustomFieldName is "Location".
    The default for AddressCustomFieldName is "Address".
    You can use any text custom field that you wish.
.EXAMPLE
    -GoogleApiKey "<GeoLocation API key here>"
    Saves the Latitude and Longitude coordinates to the custom field named Location.
.EXAMPLE
    -GoogleApiKey "<GeoLocation API key here>" -CustomFieldName "Location" -AddressCustomFieldName "Address"
    Saves the Latitude and Longitude coordinates to the custom field named Location as well as the address to Address.
.INPUTS
    None
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10
    Release Notes:
    Updated to work with either Parameters or Script Variables
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/de/nutzungsbedingungen
    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]
    $GoogleApiKey,
    [Parameter()]
    [String]
    $CustomFieldName = "Location",
    [Parameter()]
    [String]
    $AddressCustomFieldName = "Address"
)

begin {
    function Test-StringEmpty {
        param([string]$Text)
        # Returns true if string is empty, null, or whitespace
        process { [string]::IsNullOrEmpty($Text) -or [string]::IsNullOrWhiteSpace($Text) }
    }
    function Get-NearestCity {
        param (
            [double]$lat,
            [double]$lon,
            [string]$GoogleApi
        )
        try {
            $Response = Invoke-RestMethod -Uri "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lon&key=$GoogleApi"
        }
        catch {
            throw $Error[0]
        }
        return $Response.results[0].formatted_address
    }
    function Get-WifiNetwork {
        end {
            try {
                netsh.exe wlan sh net mode=bssid | ForEach-Object -Process {
                    if ($_ -match '^SSID (d+) : (.*)$') {
                        $current = @{}
                        $networks += $current
                        $current.Index = $matches[1].trim()
                        $current.SSID = $matches[2].trim()
                    }
                    else {
                        if ($_ -match '^s+(.*)s+:s+(.*)s*$') {
                            $current[$matches[1].trim()] = $matches[2].trim()
                        }
                    }
                } -Begin { $networks = @() } -End { $networks | ForEach-Object { New-Object -TypeName "PSObject" -Property $_ } }    
            }
            catch {
                # return nothing
            }
        }
    }

    # Check if Script Variables are being used
    if (-not $(Test-StringEmpty -Text $env:GoogleApiKey)) {
        $GoogleApiKey = $env:GoogleApiKey
    }
    if (-not $(Test-StringEmpty -Text $env:CustomFieldName)) {
        $CustomFieldName = $env:CustomFieldName
    }
    if (-not $(Test-StringEmpty -Text $env:AddressCustomFieldName)) {
        $AddressCustomFieldName = $env:AddressCustomFieldName
    }
    # Check if api key is set, error if not set
    if ($(Test-StringEmpty -Text $GoogleApiKey)) {
        # Both Parameter and Script Variable are empty
        # Can not combine Parameter "[Parameter(Mandatory)]" and Script Variable Required
        Write-Error "GoogleApiKey is required."
        exit 1
    }

    # Use the system's new line
    $NewLine = $([System.Environment]::NewLine)

    # Build URL with API key
    $Url = "https://www.googleapis.com/geolocation/v1/geolocate?key=$GoogleApiKey"
}
process {
    # Get WIFI network data nearby
    $WiFiData = Get-WifiNetwork |
        Select-Object @{name = 'age'; expression = { 0 } },
        @{name = 'macAddress'; expression = { $_.'BSSID 1' } },
        @{name = 'channel'; expression = { $_.Channel } },
        @{name = 'signalStrength'; expression = { (($_.Signal -replace "%") / 2) - 100 } }

    # Check if we got any number access points
    $Body = if ($WiFiData -and $WiFiData.Count -gt 0) {
        @{
            considerIp       = $true
            wifiAccessPoints = $WiFiData
        } | ConvertTo-Json
    }
    else {
        @{
            considerIp = $true
        } | ConvertTo-Json
    }

    # Get our lat,lng position
    try {
        $Response = Invoke-RestMethod -Method Post -Uri $Url -Body $Body -ContentType "application/json" -ErrorVariable Err
    }
    catch {
        Write-Error $_
        exit 1
    }

    # Save the relevant results to variable that have shorter names
    $Lat = $Response.location.lat
    $Lon = $Response.location.lng

    try {
        # Save Latitude, Longitude to the custom field from the CustomFieldName parameter
        Ninja-Property-Set -Name $CustomFieldName -Value "$Lat,$Lon"
    }
    catch {
        Write-Error "Failed to save to CustomFieldName($CustomFieldName)"
        exit 1
    }

    if ( $(Test-StringEmpty -Text $AddressCustomFieldName) -and $(Test-StringEmpty -Text $env:AddressCustomFieldName)) {
        # Both Parameter and Variable are empty
        Write-Output "$($NewLine)Location: $Lat,$Lon"
    }
    else {
        if ($(Test-StringEmpty -Text $AddressCustomFieldName)) {
            # Parameter was not used
            $AddressCustomFieldName = $env:AddressCustomFieldName
        }

        try {
            # Get City from Google API's
            # Google API: https://developers.google.com/maps/documentation/geocoding/requests-reverse-geocoding
            $Address = Get-NearestCity -lat $Lat -lon $Lon -GoogleApi $GoogleApiKey
        }
        catch {
            Write-Error "Failed to save to get nearest city."
            exit 1
        }

        try {
            # Save Lat and Lon to custom field
            Ninja-Property-Set -Name $AddressCustomFieldName -Value "$Address"
            Write-Output "$($NewLine)Location: $Address`: $Lat,$Lon"
        }
        catch {
            Write-Error "Failed to save to AddressCustomFieldName($AddressCustomFieldName)"
            exit 1
        }
    }
    exit 0
}
end {
    $ScriptVariables = @(
        [PSCustomObject]@{
            name           = "GoogleApiKey"
            calculatedName = "GoogleApiKey"
            required       = $true
            defaultValue   = $null
            valueType      = "TEXT"
            valueList      = $null
            description    = ""
        }
        [PSCustomObject]@{
            name           = "CustomFieldName"
            calculatedName = "CustomFieldName"
            required       = $false
            defaultValue   = [PSCustomObject]@{
                type  = "TEXT"
                value = "Location"
            }
            valueType      = "TEXT"
            valueList      = $null
            description    = ""
        }
    )
}

|

#Requires -Version 5.1

<#
.SYNOPSIS
    Updates Custom Fields with the location of a device based on the Google GeoLocation API.
.DESCRIPTION
    Updates Custom Fields with the location of a device based on the Google GeoLocation API.

    The CustomFieldName parameter can be used to specify which custom field to save the Latitude and Longitude coordinates to.
    The AddressCustomFieldName parameter can be used to specify which custom field to save the address to.

    This script requires a custom field to save location data in NinjaRMM.
    The default for CustomFieldName is "Location".
    The default for AddressCustomFieldName is "Address".
    You can use any text custom field that you wish.
.EXAMPLE
    -GoogleApiKey "<GeoLocation API key here>"
    Saves the Latitude and Longitude coordinates to the custom field named Location.
.EXAMPLE
    -GoogleApiKey "<GeoLocation API key here>" -CustomFieldName "Location" -AddressCustomFieldName "Address"
    Saves the Latitude and Longitude coordinates to the custom field named Location as well as the address to Address.
.INPUTS
    None
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10
    Release Notes:
    Updated to work with either Parameters or Script Variables
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]
    $GoogleApiKey,
    [Parameter()]
    [String]
    $CustomFieldName = "Location",
    [Parameter()]
    [String]
    $AddressCustomFieldName = "Address"
)

begin {
    function Test-StringEmpty {
        param([string]$Text)
        # Returns true if string is empty, null, or whitespace
        process { [string]::IsNullOrEmpty($Text) -or [string]::IsNullOrWhiteSpace($Text) }
    }
    function Get-NearestCity {
        param (
            [double]$lat,
            [double]$lon,
            [string]$GoogleApi
        )
        try {
            $Response = Invoke-RestMethod -Uri "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lon&key=$GoogleApi"
        }
        catch {
            throw $Error[0]
        }
        return $Response.results[0].formatted_address
    }
    function Get-WifiNetwork {
        end {
            try {
                netsh.exe wlan sh net mode=bssid | ForEach-Object -Process {
                    if ($_ -match '^SSID (d+) : (.*)$') {
                        $current = @{}
                        $networks += $current
                        $current.Index = $matches[1].trim()
                        $current.SSID = $matches[2].trim()
                    }
                    else {
                        if ($_ -match '^s+(.*)s+:s+(.*)s*$') {
                            $current[$matches[1].trim()] = $matches[2].trim()
                        }
                    }
                } -Begin { $networks = @() } -End { $networks | ForEach-Object { New-Object -TypeName "PSObject" -Property $_ } }    
            }
            catch {
                # return nothing
            }
        }
    }

    # Check if Script Variables are being used
    if (-not $(Test-StringEmpty -Text $env:GoogleApiKey)) {
        $GoogleApiKey = $env:GoogleApiKey
    }
    if (-not $(Test-StringEmpty -Text $env:CustomFieldName)) {
        $CustomFieldName = $env:CustomFieldName
    }
    if (-not $(Test-StringEmpty -Text $env:AddressCustomFieldName)) {
        $AddressCustomFieldName = $env:AddressCustomFieldName
    }
    # Check if api key is set, error if not set
    if ($(Test-StringEmpty -Text $GoogleApiKey)) {
        # Both Parameter and Script Variable are empty
        # Can not combine Parameter "[Parameter(Mandatory)]" and Script Variable Required
        Write-Error "GoogleApiKey is required."
        exit 1
    }

    # Use the system's new line
    $NewLine = $([System.Environment]::NewLine)

    # Build URL with API key
    $Url = "https://www.googleapis.com/geolocation/v1/geolocate?key=$GoogleApiKey"
}
process {
    # Get WIFI network data nearby
    $WiFiData = Get-WifiNetwork |
        Select-Object @{name = 'age'; expression = { 0 } },
        @{name = 'macAddress'; expression = { $_.'BSSID 1' } },
        @{name = 'channel'; expression = { $_.Channel } },
        @{name = 'signalStrength'; expression = { (($_.Signal -replace "%") / 2) - 100 } }

    # Check if we got any number access points
    $Body = if ($WiFiData -and $WiFiData.Count -gt 0) {
        @{
            considerIp       = $true
            wifiAccessPoints = $WiFiData
        } | ConvertTo-Json
    }
    else {
        @{
            considerIp = $true
        } | ConvertTo-Json
    }

    # Get our lat,lng position
    try {
        $Response = Invoke-RestMethod -Method Post -Uri $Url -Body $Body -ContentType "application/json" -ErrorVariable Err
    }
    catch {
        Write-Error $_
        exit 1
    }

    # Save the relevant results to variable that have shorter names
    $Lat = $Response.location.lat
    $Lon = $Response.location.lng

    try {
        # Save Latitude, Longitude to the custom field from the CustomFieldName parameter
        Ninja-Property-Set -Name $CustomFieldName -Value "$Lat,$Lon"
    }
    catch {
        Write-Error "Failed to save to CustomFieldName($CustomFieldName)"
        exit 1
    }

    if ( $(Test-StringEmpty -Text $AddressCustomFieldName) -and $(Test-StringEmpty -Text $env:AddressCustomFieldName)) {
        # Both Parameter and Variable are empty
        Write-Output "$($NewLine)Location: $Lat,$Lon"
    }
    else {
        if ($(Test-StringEmpty -Text $AddressCustomFieldName)) {
            # Parameter was not used
            $AddressCustomFieldName = $env:AddressCustomFieldName
        }

        try {
            # Get City from Google API's
            # Google API: https://developers.google.com/maps/documentation/geocoding/requests-reverse-geocoding
            $Address = Get-NearestCity -lat $Lat -lon $Lon -GoogleApi $GoogleApiKey
        }
        catch {
            Write-Error "Failed to save to get nearest city."
            exit 1
        }

        try {
            # Save Lat and Lon to custom field
            Ninja-Property-Set -Name $AddressCustomFieldName -Value "$Address"
            Write-Output "$($NewLine)Location: $Address`: $Lat,$Lon"
        }
        catch {
            Write-Error "Failed to save to AddressCustomFieldName($AddressCustomFieldName)"
            exit 1
        }
    }
    exit 0
}
end {
    $ScriptVariables = @(
        [PSCustomObject]@{
            name           = "GoogleApiKey"
            calculatedName = "GoogleApiKey"
            required       = $true
            defaultValue   = $null
            valueType      = "TEXT"
            valueList      = $null
            description    = ""
        }
        [PSCustomObject]@{
            name           = "CustomFieldName"
            calculatedName = "CustomFieldName"
            required       = $false
            defaultValue   = [PSCustomObject]@{
                type  = "TEXT"
                value = "Location"
            }
            valueType      = "TEXT"
            valueList      = $null
            description    = ""
        }
    )
}

 

Zugriff auf über 300 Skripte im NinjaOne Dojo

Zugang erhalten

Detailansicht

Das Skript kann in drei Hauptteile unterteilt werden:

  • Initialisierung: Das Skript beginnt mit der Definition von Parametern wie GoogleApiKey, CustomFieldName und AddressCustomFieldName. Diese Parameter dienen als Eingaben, um das Verhalten des Skripts anzupassen.
  • Hauptoperationen: Der Hauptteil des Skripts umfasst:
  • Überprüfung der verfügbaren WiFi-Netzwerke in der Umgebung des Geräts.
  • Erstellen einer Nutzlast mit WiFi-Daten und Senden an den Geolokalisierungsdienst von Google, um den Breiten- und Längengrad zu ermitteln.
  • Abruf der nächstgelegenen Stadt oder Adresse anhand der ermittelten Koordinaten.
  • Aktualisierung der benutzerdefinierten Felder in NinjaOne mit den Standortdaten.
  • Abschließende Operationen: ScriptVariablen werden initialisiert, um Daten zu speichern und bei weiteren Operationen zu helfen.

Potenzielle Anwendungsfälle

Stellen Sie sich einen IT-Fachmann, Alex, vor, der für ein Unternehmen arbeitet. Sie wurden beauftragt, alle Laptops in mehreren Niederlassungen zu prüfen. Mit diesem Skript kann Alex schnell den geografischen Standort jedes Laptops abrufen und sicherstellen, dass sie sich tatsächlich an den angegebenen Bürostandorten befinden.

Vergleiche

Der Ansatz des Skripts nutzt die Google GeoLocation API, die genaue Standortangaben liefert. Alternativen können die Verwendung nativer Windows-Standortdienste oder anderer APIs von Drittanbietern sein. Aufgrund seiner umfangreichen Daten und seiner robusten Infrastruktur ist Google jedoch die erste Wahl für solche Anwendungen, da es eine höhere Genauigkeit und eine breitere Abdeckung bietet.

FAQs

  • Funktioniert dieses Skript auch offline?
    Das Skript benötigt eine aktive Internetverbindung, um mit den Diensten von Google zu kommunizieren.
  • Gibt es eine Begrenzung für die Anzahl der Standortanfragen?
    Für die Google GeoLocation API gelten je nach Kontotyp und Abrechnungsstatus bestimmte Einschränkungen.
  • Funktioniert das Skript nur unter Windows 10?
    Die Mindestanforderung für das Betriebssystem des Skripts ist Windows 10.

Auswirkungen

Die Möglichkeit, den Standort eines Geräts zu verfolgen, ist zwar ein großartiges Instrument für die Anlagenverwaltung und die Sicherheit, wirft aber auch Fragen zum Datenschutz auf. IT-Teams müssen unbedingt sicherstellen, dass dieses Tool nach ethischen Gesichtspunkten und mit den entsprechenden Berechtigungen und Angaben verwendet wird. Unerlaubtes Tracking kann zu Verstößen gegen Datenschutzgesetze und -vorschriften führen.

Empfehlungen

  • Holen Sie immer eine ausdrückliche Genehmigung ein, bevor Sie dieses Skript auf einem Gerät ausführen.
  • Vergewissern Sie sich, dass Sie die Tarifgrenzen und Kosten im Zusammenhang mit der Google GeoLocation API kennen.
  • Regelmäßige Überprüfung und Kontrolle der Protokolle, um jeglichen Missbrauch zu verhindern.

Abschließende Überlegungen

Für MSPs und IT-Experten bietet NinjaOne eine unschätzbare Plattform zur Zentralisierung und Rationalisierung des IT-Betriebs. Die Integration solcher Skripte zum Abrufen von Gerätestandorten erweitert die Möglichkeiten von NinjaOne weiter und macht es zu einem unverzichtbaren Werkzeug für moderne IT-Landschaften. PowerShell-Skripte, insbesondere solche wie das oben zerlegte, bieten den Benutzer:innen von NinjaOne eine zusätzliche Ebene an Flexibilität und Leistung, die ihnen hilft, im dynamischen IT-Umfeld Schritt zu halten.

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.

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