Summary: Add users to random security groups, provide random passwords, and enable accounts.
Hey, Scripting Guy!
I have created a bunch of users in my sample Active Directory, but I have all these security groups that I need to populate. How can I do that with Windows PowerShell?
—BB
Hello BB,
Honorary Scripting Guy, Sean Kearney here, filling in for our good friend, Ed.
To catch up on the previous posts in this series, please read:
- Building a Demo Active Directory: Part 1
- Building a Demo Active Directory: Part 2
- Building a Demo Active Directory: Part 3
- Building a Demo Active Directory: Part 4
We’re entering in the final stretch! Populating the security groups. This is actually easier than you can imagine.
Previously, we built security groups where the names were based on the city and division, and they were targeted at those specific entries in the tree. That means if a user was in the “Ottawa/HR” organizational unit, the security group name was called “Ottawa-HR”.
We can make a minor insertion into the script. We’ll leverage the already chosen random city and division when we populate a user and generate the security group name. We’ll use the function that we created earlier, GET-GROUPINFO, to meet that need.
# Pick a Random City
$City=GET-RANDOM $Cityou
# Pick a Random Division
$Division=GET-RANDOM $DivisionOU
$GroupName=(GET-GroupInfo –City $City –Division $Division).Name
Then all we need to do is add the user to the group. We do this with the Add-ADGroupMember cmdlet:
ADD-ADGroupMember $Groupname –Members $Sam
But there are two other pieces that we should remember:
- These accounts are not enabled
- No passwords have been assigned
If the accounts have no passwords, you won’t be able to enable them. So what we should do when we create the user is include some type of password generation function.
There are so many solutions to generating a random password in Windows PowerShell. I could go on for days. For this, I adapted a simple and effective idea my friend and fellow Windows PowerShell MVP, Dmitry Sotnikov, wrote to meet this need.
We use Convert-ToSecureString because the New-ADUser cmdlet is expecting a secure string for the password:
Function GeneratePassword
{
# How many Characters Minimum?
$Length=15
# Create a password choosing everything from Character 34 to 127
1..$Length | foreach{ $Password+=([char]((Get-Random 93)+34))}
# Convert to a Secure String
$Password=Convertto-SecureString $Password -asplaintext -force
Return $Password
}
Granted, this will generate some truly unpronounceable passwords, and it may reflect the words they show in comic strips when cartoon characters let forth “magic words.” But for our demo environment , it will be fine. Of course afterwards, we’ll need to ensure that the accounts are enabled in Active Directory. For this we can use the Enable-ADAccount cmdlet, which would look like this when used for SAM account ID “jsmith”:
ENABLE-ADACCOUNT jsmith
If the password is created and enabled and it passes complexity rules, the account will show as Active. Failing that, Windows PowerShell will show an error message that indicates your password isn’t up to snuff.
So with all the pieces put into action, our final script will look like this:
Import-module ActiveDirectory
# Crude Random Password Generator
Function GeneratePassword
{
# How many Characters Minimum?
$Length=15
# Create a password choosing everying from Character 34 to 127
1..$Length | foreach{ $Password+=([char]((Get-Random 93)+34))}
# Convert to a Secure String
$Password=Convertto-SecureString $Password -asplaintext -force
Return $Password
}
Function GET-GroupInfo()
{
Param(
$City,
$Division
)
$GroupName=$City.replace(” “,””)+”-“+$Division.replace(” “,””)
$GroupDescription=”$Division in $City Access Group”
# Return the Results (This is a feature new to version 3)
[pscustomobject]@{Name=$Groupname;Description=$GroupDescription}
}
# Define OU at Base of AD for Offices
$BaseOU=”Offices”
# Provide List of Office Names
$CityOU=“Tokyo”,”Redmond”,”Ottawa”,”Madrid”,”New Orleans”,”Queensland”
# Provide List of Divisions Per Office
$DivisionOU=”Sales”,”Marketing”,”HR”,”Finance”
# DistinguishedName of Domain Root
$Domain=”DC=Contoso,DC=Local”
# Whatever the name of the $BaseOU Combined with Domain
$CompanyPath=”OU=$BaseOU,”+$Domain
# UPN Extension to the Domain
$UPN=”@contoso.local”
# Create BaseOU for Offices
NEW-ADOrganizationalUnit -name $BaseOU -path $Domain
# Gather through list of Cities
Foreach ($City in $CityOU)
{
# Create OU for City
NEW-ADOrganizationalUnit -path $CompanyPath -name $City
# Gather through list of Divisions
Foreach($Division in $DivisionOU)
{
# Create Division within City
NEW-ADOrganizationalUnit -path “OU=$City,$CompanyPath” -name $Division
# Create Group within Division and Description
$Groupdata=GET-Groupinfo –City $City –Division $Division
$GroupName=$Groupdate.Name
$GroupDescription=$Groupdata.Description
NEW-ADGroup -name $GroupName -GroupScope Global -Description $GroupDescription -Path “OU=$Division,OU=$City,$CompanyPath”
}
}
# Pull together list of CSV raw data supplied from Generator
#
$Names=IMPORT-CSV C:Scriptsamplenames.csv
# Generate 150 Random Users from pulled Raw data
For ($x=0;$x -lt 150;$x++)
{
# Pick a Random First and Last Name
$Firstname=GET-Random $Names.Firstname
$Lastname=GET-Random $Names.Lastname
$Displayname=$Lastname+”, “+$Firstname
{
# Pick a Random City
$City=GET-RANDOM $Cityou
# Pick a Random Division
$Division=GET-RANDOM $DivisionOU
$LoginID=$Firstname.substring(0,1)+$Lastname
$UserPN=$LoginID+$UPN
$Sam=$LoginID.padright(20).substring(0,20).trim()
# Define their path in Active Directory
$ADPath=”OU=$Division,OU=$City,$CompanyPath”
# Create the user in Active Directory
New-ADUser -GivenName $Givenname -Surname $Surname -DisplayName $Displayname -UserPrincipalName $UserPN -Division $Division -City $City -Path $ADPath -name $Displayname -SamAccountName $Sam –userpassword (GENERATEPASSWORD)
# Add User to appropriate Security Group
$Groupname=(GET-GroupInfo –city $City –division $Division).Name
ADD-ADGroupmember $Groupname –members $Sam
# Enable the account for access
ENABLE-ADAccount $Sam
}
}
Save this all as a script called, say, NEWDEMO.PS1, and with very little time you can generate your very own customized Active Directory structure that can contain 1000’s of users. All without clicking away on that poor little mouse.
You could customize this even further by outputting the names, generating some random computer objects, or even possibly creating more security groups. You are only limited by your imagination.
Check back tomorrow! The weekend is here, and I sense far more Windows PowerShell coolness in the midst!
I invite you to follow the Scripting Guys on Twitter and Facebook. If you have any questions, send email to scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Sean Kearney, Honorary Scripting Guy and Windows PowerShell MVP
0 comments