You are here

Powershell AD to CSV - Users changed in the last day

#This script will only work with Powershell 2.0 and .NET 3.5
#Import the account management assembly
Add-Type -AssemblyName "System.DirectoryServices.AccountManagement"
 
#Variable for the output file, whatever directories specified here must exist
$outputfile ="C:\temp\usersdaily.csv"
 
#Create the header, this will also create the file if it does not exist
"Email,FirstName,LastName,Groups,Active" | Out-File $outputfile
 
## create the context i.e. connect to the domain
$ctype = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$coptions = [System.DirectoryServices.AccountManagement.ContextOptions]::Negotiate
$context = New-Object -TypeNameSystem.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ctype,"mydomain.com","ou=users,dc=mydomain,dc=com",$coptions
 
#Here we create a filter for users who have changed in the last day
#Note that whenChanged is used instead of modifyTimeStamp because whenChanged is replicated
$editTime = (Get-Date).AddDays(-1).ToUniversalTime().ToString("yyyyMMddHHmmss") + ".0Z"
$filter = "(&(objectCategory=User)(whenChanged>=$editTime))"
 
#Create the connection and search root
$searchRoot = New-Object System.DirectoryServices.DirectoryEntry("LDAP://ou=users,dc=mydomain,dc=com")
 
#These are the properties we want returned
$propertiesToLoad = "distinguishedname","name","givenname","sn","mail"
 
#Setup the the search and load matching users
$directorySearcher = New-Object System.DirectoryServices.DirectorySearcher -ArgumentList $searchRoot,$filter,$propertiesToLoad,"OneLevel"
$users = $directorySearcher.FindAll()
$userQueryFilter = New-Object -TypeNameSystem.DirectoryServices.AccountManagement.UserPrincipal -ArgumentList $context
$searcher = New-Object System.DirectoryServices.AccountManagement.PrincipalSearcher
$searcher.QueryFilter = $userQueryFilter
 
foreach ($user in $users)
{   
    #Convert from a directory entry object to user principal...makes it easier to get the groups
    $userPrincipal = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($context,$user.Properties.distinguishedname)
 
    #Process groups
    $outputGroups = New-Object System.Collections.ArrayList
    $groups = $userPrincipal.GetAuthorizationGroups()
 
     foreach($group in $groups)
     {
         $outputGroups.Add($group.name)
     }
 
     $delimitedGroups = [string]::join('|',$outputGroups)
 
     #Print the output to a file
     $line = [string]::join(',',($userPrincipal.emailaddress,$userPrincipal.GivenName,$userPrincipal.Surname,$delimitedGroups,"true"))
     $line | Out-File $outputfile -append
}
 
& winscp.exe /console /script=c:\scripts\sftptospring.txt