A PowerShell script to export Active Directory user sAMAccountNames into a specified number of CSV files.
Sometimes it is necessary to deal with Active Directory users in bulk. A CSV file that uniquely identifies the users is required. The sAMAccountName attribute uniquely identifies users in the Active Directory domain. This is called the "pre-Windows 2000 logon name" in the Active Directory Users and Computers (ADUC) MMC. But if the users should be processed in groups, you will need a series of CSV files. A separate PowerShell script can use one of the CSV files to import the users and perform some action on each user.
An example is extending the password expiration of many users, so the password will expire MaxPassword days after each user nexts log on. You would not want all users to have their passwords expire at almost the same time. Having a series of CSV files allows you to stage the process, perhaps one group each week. Another situation is where you are modifying many users and are concerned about the replication traffic that would result.
Before running the script, make sure the values of the variables $FileName and $NumFiles meet your needs. If $FileName is "Users" and $NumFiles is 5, the CSV files "Users1.csv", "Users2.csv", "Users3.csv", "Users4.csv", and "Users5.csv" will be created. In many cases you only need one CSV file, so you would assign the value 1 to $NumFiles. Each of the files will have a header line defining the field "ID". This will be the value of the sAMAccountName of each user. As written, the files will be created in the current directory, but you can include a different path.
The Get-ADUser statement in the script can be revised for your needs. As written, the script exports all enabled users in the domain with passwords that expire. Comments in the script show how to export all enabled users, or all users. Another option would be to use the -SearchBase parameter of Get-ADUser to only consider users in an OU (and all OUs that are children of the specified OU). To only consider users that are direct members of a specified group, you would add a clause to the -Filter parameter of Get-ADUser, similar to the following:
$Users = Get-ADUser -Filter {(Enabled -eq $True) -And (memberOf -eq "cn=MyGroup,ou=Engr,ou=West,dc=Domain,dc=com")}
You must specify the full distinguished name of the group.
StaggerNTNames.txt <<-- Click here to view or download the program