Skip to main content
 

Example AD powershell query of directory information for School of Pharmacy members and affiliates.

#define constants
$UsersOU = "OU=Users, OU=Identity, DC=AD, DC=UNC, DC=EDU"

$usefullFields =
"LastLogonTimeStamp",
"createTimeStamp",
"Division",
"title",
"EmployeeID",
"samAccountName",
"GivenName",
"sn",
"Manager",
"StreetAddress",
"telephoneNumber"

$today = get-date
$sixMonthsAgo = $today.AddDays(-180)
#

# Direct members
#$people = get-aduser -LDAPFilter "(Division=45*)" -SearchScope Subtree -SearchBase $UsersOU -Properties * | SELECT $usefullFields

# Alternatively:
# Find everyone in one of the msg_unc-org-45* groups, including people whose primary 'division' isn't SOP
#
$SOPGroupPattern = "CN=MSG_unc-org-45*"
$match = @()
$people = @()
foreach ($p in (get-aduser -LDAPFilter "(ObjectClass=user)" -SearchScope Subtree `
                           -SearchBase $UsersOU `
                           -Properties "Memberof")){
  foreach ($g in $p.Memberof){
    if ($g -like $SOPGroupPattern){
      $p.samaccountname + ',' + $g
      $match += $p.DistinguishedName
      break
    }
  }
}
foreach ($m in $match){
    $people += get-aduser -LDAPFilter "(DistinguishedName=$m)" -Properties * | Select $usefullFields
}

# END Alternatively

$otherPeople = @() # Managers outside SOP


foreach ($p in $people){
  if ($p.Manager){
    $isSOP = 0
    $i = get-aduser -Identity $p.Manager -Properties * | SELECT "EmployeeID"
    $p.Manager = $i.EmployeeID # translate DN to PID
    foreach ($q in $people){
      if ([Int32]$q.EmployeeID -eq [Int32]$i.EmployeeID){
        $isSOP = 1
        break
      }
    }
    if (!$isSOP){
      $t = $i.EmployeeID
      $isDupe = 0
      foreach ($o in $otherPeople){
        if ([Int32]$t -eq [Int32] $o.EmployeeID){
          $isDupe = 1
          break
        }
      }
      if (!$isDupe){
        $otherPeople += get-aduser -LDAPFilter "(EmployeeID=$t)" -SearchScope Subtree `
                        -SearchBase $UsersOU -Properties * | SELECT $usefullFields
      }
    }
  }
  
  if ($p.LastLogonTimeStamp){
    $lastActive = [datetime]::FromFileTime($p.LastLogonTimeStamp).ToString('g') # translate to standard time encoding
    if ([datetime]$lastActive -lt $sixMonthsAgo){
      $p.LastLogonTimeStamp = 0 # Active is false
    }
    else{ $p.LastLogonTimeStamp = 1 }
  }
}

foreach ($p in $otherPeople){
  if ($p.Manager){
    $i = get-aduser -Identity $p.Manager -Properties * | SELECT "EmployeeID"
    $p.Manager = $i.EmployeeID # translate DN to PID
  }
  if ($p.LastLogonTimeStamp){
    $lastActive = [datetime]::FromFileTime($p.LastLogonTimeStamp).ToString('g') # translate to standard time encoding
    if ([datetime]$lastActive -lt $sixMonthsAgo){
      $p.LastLogonTimeStamp = 0 # Active is false
    }
    else{ $p.LastLogonTimeStamp = 1 }
  }
}

$people | export-csv -delimiter '|' ourpeople.csv
$otherPeople | export-csv -Append -Delimiter '|' ourpeople.csv
Comments are closed.