Skip to content

Instantly share code, notes, and snippets.

@IISResetMe
Last active September 25, 2017 23:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IISResetMe/9346fe09a15966b25a7da53bb3e827b5 to your computer and use it in GitHub Desktop.
Save IISResetMe/9346fe09a15966b25a7da53bb3e827b5 to your computer and use it in GitHub Desktop.
Middle Management Reporting in PowerShell
$Properties = 'employeeID'
# Retrieve all workers with their "manager" attribute
Get-ADUser -Filter "title -like '*worker*'" -Properties @('manager';$Properties) |ForEach-Object {
# Iterate over workers, retrieve each workers manager individually
[pscustomobject]@{
Worker = $_
Manager = Get-ADUser -Identity $_.manager -Properties $Properties -ErrorAction SilentlyContinue
}
}
$Properties = 'employeeID'
# Retrieve all workers with their "manager" attribute + desired filter attribute
$Users = Get-ADUser -Properties @('manager','title';$Properties)
# Create a DN lookup table up front
$LookUpTable = $Users |ForEach-Object {$t = @{}} {
$LookUpTable[$_.DistinguishedName] = $_
} {return $t}
$Users |Where-Object title -like *worker* |ForEach-Object {
# Iterate over workers, fetch each workers manager from already populated lookup table
[pscustomobject]@{
Worker = $_
Manager = $LookUpTable[$_.manager]
}
}
using namespace System.Collections
using namespace Microsoft.ActiveDirectory.Management
class ADUserCache
{
hidden [string[]]$Properties
hidden [string]$KeyAttribute = 'DistinguishedName'
hidden [IDictionary]$LookupTable
ADUserCache([string[]]$Properties){
$this.LookupTable = @{}
$this.Properties = $Properties
}
[ADUser]Get([string]$Key){
if($this.LookupTable.Contains($Key)){
return $this.LookupTable[$Key]
}
else{
return ($this.LookupTable[$Key] = Get-ADUser -Identity $Key -Properties $this.Properties -SilentlyContinue)
}
}
}
$Properties = 'employeeID'
$cache = [ADUserCache]::new(@($Properties))
# Retrieve all workers with their "manager" attribute
Get-ADUser -Filter "title -like '*worker*'" -Properties @('manager';$Properties) |ForEach-Object {
# Iterate over workers, retrieve each workers manager from cache instance (which will transparently fetch it if it doesn't exist)
[pscustomobject]@{
Worker = $_
Manager = $cache.Get($_.manager)
}
}
$Properties = 'employeeID'
# Create an empty DN lookup table
$LookUpTable = @{}
# Retrieve all workers with their "manager" attribute
Get-ADUser -Filter "title -like '*worker*'" -Properties @('manager';$Properties) |ForEach-Object {
# Iterate over workers, retrieve each workers manager from table if exists, otherwise query and cache
[pscustomobject]@{
Worker = $_
Manager = if($LookUpTable.ContainsKey($_.manager)){
$LookUpTable[$_.manager]
}
else{
($LookUpTable[$_.manager] = Get-ADUser -Identity $_.manager -Properties $Properties -ErrorAction SilentlyContinue)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment