$results = New-Object -TypeName PSCustomObject
# Add HostName, Timestamp, and Source properties
$results | Add-Member -MemberType NoteProperty -Name "HostName" -Value $env:COMPUTERNAME
$results | Add-Member -MemberType NoteProperty -Name "Timestamp" -Value (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
$results | Add-Member -MemberType NoteProperty -Name "Source" -Value "AD.ps1"
# Initialize ErrorException property
$errorException = $null
# Define counters
$counters = @(
"\Memory\Cache Faults/sec",
"\Memory\Cache Bytes",
"\Memory\Cache Bytes Peak",
"\Memory\Long-Term Average Standby Cache Lifetime (s)",
"\NTDS\LDAP Client Sessions",
"\NTDS\LDAP Searches/sec",
"\NTDS\LDAP Successful Binds/sec",
"\System\Context Switches/sec",
"\System\Processor Queue Length",
"\ADWS\Allocated Connections",
"\ADWS\Possible Connections",
"\ADWS\Number of Directory Instances",
"\ADWS\Custom Action LDAP Cache Maximum Possible Size",
"\ADWS\Custom Action DS RPC Cache Maximum Possible Size",
"\NTDS\LDAP Outbound Bytes",
"\NTDS\LDAP Outbound Bytes/sec",
"\NTDS\Links added",
"\NTDS\ATQ Threads Total",
"\NTDS\Approximate highest DNT",
"\NTDS\DRA Highest USN Committed (Low part)",
"\NTDS\DRA Highest USN Issued (Low part)",
"\NTDS\DS % Reads from KCC",
"\NTDS\DS % Reads from LSA",
"\NTDS\DS % Reads Other",
"\NTDS\DS % Searches from KCC"
)
# Retrieve all counters at once
try {
$counterValues = Get-Counter -Counter $counters -MaxSamples 1 -ErrorAction SilentlyContinue
$counterValues.CounterSamples | ForEach-Object {
$name = $_.Path.Split('\')[-1].Replace(" ", "") # Simplify name extraction
$results | Add-Member -MemberType NoteProperty -Name $name -Value $_.CookedValue
}
} catch {
$errorException = $_.Exception.Message
}
# Add ErrorException property
$results | Add-Member -MemberType NoteProperty -Name "Error" -Value $errorException
# Print the results to STDOUT in JSON
$results | ConvertTo-Json