Categories
Uncategorized

Pull users from AD

I needed:

  • users from AD with specific OU
  • non disabled
  • filter by department
  • manager details
  • last logon time and other details

For pulling active (non disabled) users belonging to specific group along with their managers name into CSV, I made following powershell script. Output is then loaded into excel and send automatically to managers for approval. Department “x” means a special user which will be omitted.

$FileName="c:\somepath\somefile.txt"

if (Test-Path $FileName) 
{
  Remove-Item $FileName
}

$fileEncoding = "Default"

Out-File -encoding $fileEncoding $FileName

$dn = (Get-ADGroup 'Some group').DistinguishedName
$users = Get-ADUser -Filter " memberof -RecursiveMatch '$dn'" -Properties $properties

Foreach ($User in $Users)
{
 if ($user.Enabled -and ($user.Department -ne "x")) {      
  $userName=$user.UserPrincipalName
  $ou=$user.DistinguishedName.split(',OU=')[5]
  $man=$user.Manager
  $mail=$user.mail
 
  if ($man -ne $null) {	  
	$mgrUsr=(Get-ADUser $man -Properties UserPrincipalName,DisplayName,mail)
	$mngr=$mgrUsr.UserPrincipalName + ";" +$mgrUsr.mail + ";" + $mgrUsr.DisplayName
  } else {
	$mngr=";;"  
  }
  ($user.UserPrincipalName + ";" +  $user.cn + ";" + $user.LastLogonDate + ";" + $ou + ";" + ";" + $mngr  + ";" + $user.Department)  | Out-File -encoding $fileEncoding $FileName -Append 
  
 } 
}

for VPS hosting go here:

Leave a Reply

Your email address will not be published. Required fields are marked *