You are here

Powershell AD to CSV - All users in an Organizational Unit

#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\springusers.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=user,dc=mydomain,dc=com",$coptions
$userQueryFilter = New-Object -TypeNameSystem.DirectoryServices.AccountManagement.UserPrincipal -ArgumentList $context
$searcher = New-Object System.DirectoryServices.AccountManagement.PrincipalSearcher
$searcher.QueryFilter = $userQueryFilter
$users = $searcher.FindAll()
 
#Loop through the users
foreach ($user in $users)
{
    $outputGroups = New-Object System.Collections.ArrayList
 
    #This will get all of the groups and nested groups
    $groups = $user.GetAuthorizationGroups()
 
    foreach($group in $groups)
    {
        $outputGroups.Add($group.name)
    }
 
    #Format the output
    $delimitedGroups = [string]::join('|',$outputGroups)
    $line =  [string]::join(',',($user.emailaddress,$user.GivenName,$user.Surname,$delimitedGroups,"true"))
    $line | Out-File $outputfile -append
}
 
& winscp.exe /console /script=c:\scripts\sftptospring.txt