Creating Test Accounts on a Windows 2008 R2 DC with PowerShell

Recently I had to rebuild my lab do to that I had cloned a bunch of VM’s and forgot to run sysprep on them. This caused problems do to link SID’s when I installed Exchange 2010 in my home lab so I decided to rebuild the whole AD and services in it. So I decided to share how I created 100 test accounts on an isolated part of my lab network.

After installing the Active Directory Service and making the changes to DNS so it would forward to the proper DNS and made sure I had a Reverse Lookup Zone I wanted to create 100 test domain accounts. I normally use cmd.exe with dsadd.exe command, but this time I wanted to do it using PowerShell and this is with what I came up with as a command:

  1: import-module activedirectory
  2: (1..100) | foreach {New-ADUser -SamAccountName "User$($_.tostring())" -Name "User$($_.tostring())" -DisplayName "User$($_.tostring())" -AccountPassword (ConvertTo-SecureString -AsPlainText "P@ssword$($_.tostring())" -Force) -Enabled $true -EmailAddress "user$($_.tostring())" }

The commands are broken as so:

  • On line 1 I import the Active Directory PowerShell Module on the DC. If you want to see the cmdlets available on this module you can run  Get-Command -Module activedirectory this will list all of the cmdlets available to us to manage Active Directory.
  • On line 1 I generated a range from 1 to 100 and piped it to the cmdlet ForEach-Object and gave I a code block to run the cmdlet New-ADUser. To get more info on this cmdlet I invite you to run Get-Help New-ADUser –Full this will give you the full help plus examples of the cmdlet. Since the default variable of each object processed by the pipe is $_ and in the case of a range what I’m getting are Int32 objects I need to use the method of .ToString() to convert them to string and I use $() inside a double quoted string to expand the variable. What I do for each user I created was:
    • Set a Name
    • Set a Display Name
    • Set SAM Account Name
    • Set the Password. Now the cmdlet requires a secure string as value for the parameter, for this I used the ConvertTo-SecureString cmdlet to generate one from a plaintext quoted string.
    • Enable the account and set an email address since I will be installing Exchange later in this environment.

I do hope you find this useful and informative as always.