sábado, 18 de julio de 2015

Power Shell - Export Active Directory Users

Why I need to export my Active Directory users/accounts ?

Working as a System Administrator sometimes (actually always) is a bit messy organise the users and accounts that you have in the Active Directory.
Sometimes do you have old users than left the company years ago, or maybe you created twice, or three times the same Service account.

However, it's a good practice to have a list of all your users in an Excel document, to take some actions about the organisation/administration of your Active Directory.

Here is a Power Shell script to export all your users to a CSV file, after that you will be able to apply filters and look for users, accounts that you don't need anymore.

The Script


 

#Path to export the CSV file, the folder must to be created before.
$path = Split-Path -Parent "C:\Export_AD_Users_to_CSV\*.*"

#Variable for the date.
$LogDate = get-date -f yyyyMMddhhmm

#Define CSV and log file location variables
#they have to be on the same location as the script
$csvFile = $path + "\ALLADUsers_$LogDate.csv"

#Import the AD Module
Import-Module ActiveDirectory

#Set the OU to do the base search for all user accounts.
$SearchBase = "OU=Domain Controllers,DC=contoso,DC=com"

#Get Admin account credential.
$GetAdminact = Get-Credential

#Define variable for a server with AD web services installed.
$ADServer = 'Server01'

#Define "Account Status" 
$AllADUsers = Get-ADUser -server $ADServer `
-Credential $GetAdminact -SearchBase $SearchBase `
-Filter * -Properties * | Where-Object {$_.info -NE 'Migrated'}

#Select the properties that you want to export.
$AllADUsers | 
Select-Object @{Label = "First Name";Expression = {$_.GivenName}},
@{Label = "Last Name";Expression = {$_.Surname}},
@{Label = "Display Name";Expression = {$_.DisplayName}},
@{Label = "Logon Name";Expression = {$_.sAMAccountName}},
@{Label = "Full address";Expression = {$_.StreetAddress}},
@{Label = "Job Title";Expression = {$_.Title}},
@{Label = "Directorate";Expression = {$_.Description}},
@{Label = "Department";Expression = {$_.Department}},
@{Label = "Phone";Expression = {$_.telephoneNumber}},
@{Label = "Email";Expression = {$_.Mail}},
@{Label = "Last LogOn Date";Expression = {$_.lastlogondate}} |

Export-Csv -Path $csvfile -NoTypeInformation

No hay comentarios:

Publicar un comentario