Fetching Active Directory users and computers and GP applied to them

Hello friends,
I am trying to implement fetching active directory users and computers, if possible, in addition to listing which group policies are active on specific users. I am using Grafana to visualize this data.
I have checked a telegraf input plugin called win_perf_counters, but I am not getting the data I am looking for with this plugin. Can someone support me with this, please?

Hello @Amanuel_Elhanan,
You’ll probably want to use the execd input plugin with telegraf. Telegraf can’t natively query AD, but you can write a PowerShell script that:

  • Queries AD for users and computers
  • Lists GPOs applied to users or OUs
  • Outputs the data as JSON or InfluxDB line protocol

The telegraf config might look like:

[[inputs.exec]]
  commands = ["powershell.exe -File 'C:\\Scripts\\ad_users.ps1'"]
  data_format = "influx"
  interval = "10m"

I haven’t tested it but the script might look like:

Import-Module ActiveDirectory
Import-Module GroupPolicy

# 1. Output all users with last logon in seconds since last logon
$users = Get-ADUser -Filter * -Property LastLogonDate
foreach ($user in $users) {
    $name = $user.SamAccountName
    $lastLogon = if ($user.LastLogonDate) { 
        [int]((Get-Date).ToUniversalTime() - $user.LastLogonDate.ToUniversalTime()).TotalSeconds 
    } else { 
        -1 
    }
    Write-Output "ad_user,user=$name last_logon_seconds=$lastLogon"
}

# 2. Output all computers with OS info
$computers = Get-ADComputer -Filter * -Property OperatingSystem,LastLogonDate
foreach ($computer in $computers) {
    $name = $computer.Name
    $os = $computer.OperatingSystem -replace " ", "\ "  # Escape spaces
    $lastLogon = if ($computer.LastLogonDate) { 
        [int]((Get-Date).ToUniversalTime() - $computer.LastLogonDate.ToUniversalTime()).TotalSeconds 
    } else { 
        -1 
    }
    Write-Output "ad_computer,computer=$name os=\"$os\",last_logon_seconds=$lastLogon"
}

# 3. List GPO inheritance for a set of OUs
$OUs = @(
    "OU=Sales,DC=yourdomain,DC=com",
    "OU=IT,DC=yourdomain,DC=com"
)

foreach ($ou in $OUs) {
    try {
        $inheritance = Get-GPInheritance -Target $ou
        foreach ($gpo in $inheritance.GpoLinks) {
            $gpoName = $gpo.DisplayName -replace " ", "\ "
            $enforced = $gpo.Enforced
            $enabled = -not $gpo.Disabled
            Write-Output "ad_gpo,ou=\"$ou\",gpo=\"$gpoName\" enforced=$enforced,enabled=$enabled"
        }
    } catch {
        Write-Output "ad_gpo,ou=\"$ou\" error=true"
    }
}

@skartikey might have more/better ideas.

2 Likes

Hello @Anaisdg thank you so much for your suggestion. I tried creating the script you shared and then added the config on telegraf, After restarting both telegraf and influxdb I couldn’t see any filter for a given measurement. is there anything I am missing here?