Create a batch of Active Directory user accounts quickly
Tuesday, April 21, 2009 at 16:46 I was asked, rather tentatively, if I could setup 300 user accounts in the Active Directory for a project. I say tentatively because the person doing the asking thought that it would probably take me a day, or all week, or something. So this is how I actually did it with PowerShell in 30 seconds flat:
1..300 | ForEach-Object{
New-QADUser -Name $("user{0:0000}" -f $_) -ParentContainer "OU=Test Users,DC=domain,DC=com" -UserPassword "Abcd12234!"
}
I'm using a range there to give me 1 to 300, then for each of those, I'm using Quest's NewQADUser cmdlet to create a user with the name $("user{0:0000}" -f $_) - which is odd, but I'll step through it...
It's enclosed in $(), which is a subparse control - it tells the parser to do whatever's in the parentheses first. So what's in the parentheses? Well that's just a .Net formatting syntax. It has "user" in the string, so these user names are going to start "user", then {0:0000}. The 0: says it's a numerical syntax, then 0000 says it has four positions, for the item to the right of the formatting operator (-f), which is the item currently on the pipeline ($_). So while the number range is passing 1 down the pipeline, we'll get 0001, and when it is passing 300, we'll get 0300. That is to say that we'll get "user0001" to "user0300".
If that formatting stuff doesn't make a lot of sense, this might help:
1..3 | ForEach-Object{"{0:00}" -f $_}
would give you
01
02
03
If you were talking about financial values (in GBP), you might want to do
1..3 | ForEach-Object{"£{0:0.00}" -f $_}
which gives
£1.00
£2.00
£3.00
or say you have a large number that you want to put commas in to make it more readable, and limit to 2 decimal places, you could use
"{0:0,000,000,000.00}" -f 1234567890.12345
which returns
1,234,567,890.12
I hope that helps understand the syntax a bit better.
Incidentally, I know I've talked about using Quest's Active Directory cmdlets before, but I think it's worth repeating until everyone knows about them (even though the forthcoming release of Server 2008 R2 has its own set of native AD cmdlets).



Reader Comments (1)
Thanks for information!