-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNew-RandomADUser.psm1
More file actions
70 lines (60 loc) · 2.78 KB
/
New-RandomADUser.psm1
File metadata and controls
70 lines (60 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#Requires -Modules ActiveDirectory
# Function to generate random Active Directory users
function New-RandomADUser {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory = $true, HelpMessage = "The domain name (e.g., contoso.com)")]
[string]$Domain,
[Parameter(Mandatory = $true, HelpMessage = "The organizational unit (OU) to create users in (e.g., 'OU=Users,DC=contoso,DC=com')")]
[string]$OU,
[Parameter(Mandatory = $false, HelpMessage = "The number of users to generate (default: 1)")]
[int]$Count = 1,
[Parameter(Mandatory = $false, HelpMessage = "Prefix for usernames (e.g., 'test')")]
[string]$Prefix = ""
)
# Function to generate a random password
function Get-RandomPassword {
$passwordChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()"
$passwordLength = 16
$password = -join ($passwordChars | Get-Random -Count $passwordLength)
return $password
}
# Function to generate a random name
function Get-RandomName {
$firstNames = Get-Content -Path "$PSScriptRoot\files\firstnames.txt"
$lastNames = Get-Content -Path "$PSScriptRoot\files\lastnames.txt"
$firstName = Get-Random -InputObject $firstNames
$lastName = Get-Random -InputObject $lastNames
return @{ FirstName = $firstName; LastName = $lastName }
}
# Main loop to create users
for ($i = 0; $i -lt $Count; $i++) {
$randomName = Get-RandomName
$firstName = $randomName.FirstName
$lastName = $randomName.LastName
$username = "$Prefix$($firstName.ToLower()).$($lastName.ToLower())"
$userPrincipalName = "$username@$Domain"
$password = Get-RandomPassword
if ($PSCmdlet.ShouldProcess("$Domain\$username", "Create Active Directory User")) {
try {
New-ADUser -Name "$firstName $lastName" `
-GivenName $firstName `
-Surname $lastName `
-SamAccountName $username `
-UserPrincipalName $userPrincipalName `
-AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) `
-Path $OU `
-Enabled $true `
-ChangePasswordAtLogon $true `
-ErrorAction Stop
Write-Verbose "Created user: $username (Password: $password)"
Write-Output "User '$username' created successfully."
}
catch {
Write-Error "Failed to create user '$username': $($_.Exception.Message)"
}
}
}
}
# Export the function
Export-ModuleMember -Function New-RandomADUser