Wednesday, April 16, 2014

Managing test AD accounts in powershell

It is common that different application teams may require a block of test accounts to test different roles in an application.  So you may come across requests to create large numbers of accounts or modify them (or a subset of them).  Since there are many examples of account creation around the net, I don't want to repeat what is already done.  You can define what you want in your user and use the New-ADUser cmdlet to create them.  Often, users may be a standard name with a numeric identifier attached.  In this case you can do something like this:

for ($i = 0; $i -lt 300; $i++) {

 #for names of the same length
 $name = "testuser" + ([string]$i).padleft(3,'0')
 #or just by numeric
 #$name = "testuser" + $i
 
 new-aduser [enter options and use $name]
 
}

Depending on the desired name format, you can adjust as needed.  When requests come in to change a subset of these accounts, you need to find a way to easily search the correct ones.  You can do this by text matching, or if you were planning ahead, you could have put a numeric identifier in an unused attribute of the user object to help with searches.  Let's assume you want to text match the user names to make changes to TestUser051 through TestUser100.  You can pull the full list of test users and use the $matches special variable in powershell to work with the digits:

$users = get-aduser -LDAPFilter "(&(samaccountname=testuser*)(objectclass=user))"| where {$_.name -match "\d{3}$" -and ([int]$matches[0] -ge 51 -and [int]$matches[0] -le 100) }

Here we grab all users that match testuser* using get-aduser.  This pipes to the where-object commandlet which matches the last 3 digits.  These digits are stored in the $matches result.  So we pull that data, convert it to a number and ensure that it is in our range.  This leaves the $users variable full of the results we want, and we can later pipe this to foreach loops or other commands to make whatever changes we need.

No comments:

Post a Comment