├── users-example.csv ├── LICENSE ├── README.md └── On-Prem-AD-User-Creator.ps1 /users-example.csv: -------------------------------------------------------------------------------- 1 | Firstname,Lastname 2 | John,Shepard 3 | Jane,Shepard 4 | David,Anderson -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | Copyright (c) 2024 Mike Galvin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # On-Prem AD User Creator Utility 2 | 3 | ## Configurable Script For Creating Active Directory User Accounts 4 | 5 | For full change log and more information, [visit my site.](https://gal.vin/utils/on-prem-ad-user-creator-utility/) 6 | 7 | On-Prem AD User Creator Utility is available from: 8 | 9 | * [GitHub](https://github.com/Digressive/On-Prem-AD-User-Creator-Utility) 10 | 11 | Please consider supporting my work: 12 | 13 | * Support with [Github Sponsors](https://github.com/sponsors/Digressive). 14 | * Support with a one-time donation using [PayPal](https://www.paypal.me/digressive). 15 | 16 | Please report any problems via the 'issues' tab on GitHub. 17 | 18 | Thanks 19 | -Mike 20 | 21 | ## Features and Requirements 22 | 23 | * Requires the Active Directory PowerShell module be installed. 24 | * Requires A CSV file containing the FirstName and LastName of each user to create. 25 | * Configurable list of groups to add new users to. 26 | * Randomly generated passwords for each user. 27 | * User names are generated from first name & a 3 digit random number. 28 | * The utility requires at least PowerShell 5.0. 29 | * Tested on Windows 11, Windows 10, Windows Server 2022, Windows Server 2019, Windows Server 2016. 30 | 31 | ## Generating A Password File For SMTP Authentication 32 | 33 | The password used for SMTP server authentication must be in an encrypted text file. To generate the password file, run the following command in PowerShell on the computer and logged in with the user that will be running the utility. When you run the command, you will be prompted for a username and password. Enter the username and password you want to use to authenticate to your SMTP server. 34 | 35 | Please note: This is only required if you need to authenticate to the SMTP server when send the log via e-mail. 36 | 37 | ``` powershell 38 | $creds = Get-Credential 39 | $creds.Password | ConvertFrom-SecureString | Set-Content c:\scripts\ps-script-pwd.txt 40 | ``` 41 | 42 | After running the commands, you will have a text file containing the encrypted password. When configuring the -Pwd switch enter the path and file name of this file. 43 | 44 | ## Configuration 45 | 46 | Here’s a list of all the command line switches and example configurations. 47 | 48 | | Command Line Switch | Description | Example | 49 | | ------------------- | ----------- | ------- | 50 | | -CSV | The path of the csv file containing the user info. Please see the users-example.csv file for how to structure your own file. | [path\]user-list.csv | 51 | | -OU | The Organizational Unit to create the users in. If none is configured the default Computers OU will be used. | 'OU=User_Accounts,DC=contoso,DC=com' | 52 | | -UPN | The Universal Principal Name the users should be configured with. If none is configured the forest name will be used. | [contoso.com] | 53 | | -HomeLetter | The drive letter to use for the home drive path. | [drive letter] | 54 | | -HomePath | The path where the location of the home drive should reside. | [path\] | 55 | | -Groups | The name of the group(s) separated by a comma that all the new users should be a member of. | [UserGroup1,UserGroup2] | 56 | | -L | The path to output the log file to. | [path\] | 57 | | -LogRotate | Remove logs produced by the utility older than X days | [number] | 58 | | -NoBanner | Use this option to hide the ASCII art title in the console. | N/A | 59 | | -Help | Display usage information. No arguments also displays help. | N/A | 60 | | -Subject | Specify a subject line. If you leave this blank the default subject will be used | "'[Server: Notification]'" | 61 | | -SendTo | The e-mail address the log should be sent to. For multiple address, separate with a comma. | [example@contoso.com] | 62 | | -From | The e-mail address the log should be sent from. | [example@contoso.com] | 63 | | -Smtp | The DNS name or IP address of the SMTP server. | [smtp server address] | 64 | | -Port | The Port that should be used for the SMTP server. If none is specified then the default of 25 will be used. | [port number] | 65 | | -User | The user account to authenticate to the SMTP server. | [example@contoso.com] | 66 | | -Pwd | The txt file containing the encrypted password for SMTP authentication. | [path\]ps-script-pwd.txt | 67 | | -UseSsl | Configures the utility to connect to the SMTP server using SSL. | N/A | 68 | 69 | ## Example 70 | 71 | ``` txt 72 | [path\]On-Prem-AD-User-Creator.ps1 -csv [path\]user-list.csv 73 | ``` 74 | 75 | This will create new users from the names in the csv file. The user objects will be created in the 'Computers' builtin OU. 76 | 77 | ## Change Log 78 | 79 | ### 2023-04-28: Version 23.04.28 80 | 81 | * Removed specific SMTP config info from config report. 82 | * Added script update checker - shows if an update is available in the log and console. If the internet is not reachable it silently errors out. 83 | 84 | ### 2022-06-14: Version 22.06.06 85 | 86 | * Added new feature: log can now be emailed to multiple addresses. 87 | * Added checks and balances to help with configuration as I'm very aware that the initial configuration can be troublesome. Running the utility manually is a lot more friendly and step-by-step now. 88 | * Added -Help to give usage instructions in the terminal. Running the script with no options will also trigger the -help switch. 89 | * Cleaned user entered paths so that trailing slashes no longer break things or have otherwise unintended results. 90 | * Added -LogRotate [days] to removed old logs created by the utility. 91 | * Streamlined config report so non configured options are not shown. 92 | * Added donation link to the ASCII banner. 93 | * Cleaned up code, removed unneeded log noise. 94 | 95 | ### 2021-12-08: Version 21.12.08 96 | 97 | * Configured logs path now is created, if it does not exist. 98 | * Added OS version info. 99 | * Added Utility version info. 100 | * Added Hostname info. 101 | 102 | ### 2021-09-20: Version 21.09.20 103 | 104 | * Added code to make sure sam account name will never be more than 19 characters, due to the default sam account name length being 20 characters. 105 | 106 | ### 2021-09-15: Version 21.09.15 107 | 108 | * Completely rewritten to streamline the user creation process. 109 | * User passwords are now randomly generated. 110 | * Added option to add users to multiple groups. 111 | * Utility will find groups based on the AD name. No more having to specify the whole DN. 112 | * Added ASCII banner art when run in the console. 113 | * Added option to disable the ASCII banner art. 114 | * Added an option to specify the Port for SMTP communication. 115 | 116 | ### 2019-09-04 v1.6 117 | 118 | * Added custom subject line for e-mail. 119 | 120 | ### 2017-10-16 v1.5 121 | 122 | * Changed SMTP authentication to require an encrypted password file. 123 | * Added instructions on how to generate an encrypted password file. 124 | 125 | ### 2017-10-07 v1.4 126 | 127 | * Added necessary information to add the script to the PowerShell Gallery. 128 | 129 | ### 2017-09-13 v1.3 130 | 131 | * Added check for existence of user before attempting to create user. 132 | * Improved logging to handle the above change. 133 | 134 | ### 2017-07-22 v1.2 135 | 136 | * Improved code commenting for documentation purposes. 137 | * Added authentication and SSL options for e-mail notification. 138 | -------------------------------------------------------------------------------- /On-Prem-AD-User-Creator.ps1: -------------------------------------------------------------------------------- 1 | <#PSScriptInfo 2 | 3 | .VERSION 23.04.28 4 | 5 | .GUID eaaca86c-2a1f-4caf-b2f9-05868186d162 6 | 7 | .AUTHOR Mike Galvin Contact: digressive@outlook.com 8 | 9 | .COMPANYNAME Mike Galvin 10 | 11 | .COPYRIGHT (C) Mike Galvin. All rights reserved. 12 | 13 | .TAGS Active Directory User Creation CSV Import 14 | 15 | .LICENSEURI https://github.com/Digressive/On-Prem-AD-User-Creator-Utility?tab=MIT-1-ov-file 16 | 17 | .PROJECTURI https://gal.vin/utils/on-prem-ad-user-creator-utility/ 18 | 19 | .ICONURI 20 | 21 | .EXTERNALMODULEDEPENDENCIES 22 | 23 | .REQUIREDSCRIPTS 24 | 25 | .EXTERNALSCRIPTDEPENDENCIES 26 | 27 | .RELEASENOTES 28 | 29 | #> 30 | 31 | <# 32 | .SYNOPSIS 33 | On-Prem AD User Creator Utility - Configurable Script to create new Active Directory user accounts. 34 | 35 | .DESCRIPTION 36 | This script will create AD users based on first and last names in a specified CSV file. 37 | Run with -help or no arguments for usage. 38 | #> 39 | 40 | ## Set up command line switches. 41 | [CmdletBinding()] 42 | Param( 43 | [alias("CSV")] 44 | $UsersList, 45 | [alias("OU")] 46 | $OrgUnit, 47 | [alias("UPN")] 48 | $AdUpn, 49 | [alias("HomeLetter")] 50 | $HomeDrive, 51 | [alias("HomePath")] 52 | $HomeUncUsr, 53 | [alias("Groups")] 54 | $AdGrps, 55 | [alias("L")] 56 | $LogPathUsr, 57 | [alias("LogRotate")] 58 | $LogHistory, 59 | [alias("Subject")] 60 | $MailSubject, 61 | [alias("SendTo")] 62 | $MailTo, 63 | [alias("From")] 64 | $MailFrom, 65 | [alias("Smtp")] 66 | $SmtpServer, 67 | [alias("Port")] 68 | $SmtpPort, 69 | [alias("User")] 70 | $SmtpUser, 71 | [alias("Pwd")] 72 | [ValidateScript({Test-Path -Path $_ -PathType Leaf})] 73 | $SmtpPwd, 74 | [switch]$UseSsl, 75 | [switch]$Help, 76 | [switch]$NoBanner) 77 | 78 | If ($NoBanner -eq $False) 79 | { 80 | Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " 81 | ____ ____ ___ ____ 82 | / __ \____ / __ \________ ____ ___ / | / __ \ Mike Galvin 83 | / / / / __ \______/ /_/ / ___/ _ \/ __ '__ \ / /| | / / / / https://gal.vin 84 | / /_/ / / / /_____/ ____/ / / __/ / / / / / / ___ |/ /_/ / 85 | \____/_/_/_/ /_/ /_/ __\___/_/ /_/ /_/ /_/__|_/_____/ __ ____ _ ___ __ 86 | / / / /_______ _____ / ____/_______ ____ _/ /_____ _____ / / / / /_(_) (_) /___ __ 87 | / / / / ___/ _ \/ ___/ / / / ___/ _ \/ __ '/ __/ __ \/ ___/ / / / / __/ / / / __/ / / / 88 | / /_/ (__ ) __/ / / /___/ / / __/ /_/ / /_/ /_/ / / / /_/ / /_/ / / / /_/ /_/ / 89 | \____/____/\___/_/ \____/_/ \___/\__,_/\__/\____/_/ \____/\__/_/_/_/\__/\__, / 90 | /____/ 91 | Version 23.04.28 92 | See -help for usage Donate: https://www.paypal.me/digressive 93 | " 94 | } 95 | 96 | If ($PSBoundParameters.Values.Count -eq 0 -or $Help) 97 | { 98 | Write-Host -Object "Usage: 99 | From a terminal run: [path\]On-Prem-AD-User-Creator.ps1 -csv [path\]user-list.csv 100 | This will create new users from the names in the csv file. 101 | The user objects will be created in the 'Computers' builtin OU. 102 | 103 | To set the users UPN use: -upn [domain.name] 104 | To set where the user objects are created: -ou [""'Full OU DN path'""] 105 | To set the Home letter and Home path: -HomeLetter [drive letter] -HomePath [path] 106 | To set which group(s) the new users should be a member of: -Groups [UserGroup1,UserGroup2] 107 | 108 | To output a log: -L [path\]. 109 | To remove logs produced by the utility older than X days: -LogRotate [number]. 110 | Run with no ASCII banner: -NoBanner 111 | 112 | To use the 'email log' function: 113 | Specify the subject line with -Subject ""'[subject line]'"" If you leave this blank a default subject will be used 114 | Make sure to encapsulate it with double & single quotes as per the example for Powershell to read it correctly. 115 | 116 | Specify the 'to' address with -SendTo [example@contoso.com] 117 | For multiple address, separate with a comma. 118 | 119 | Specify the 'from' address with -From [example@contoso.com] 120 | Specify the SMTP server with -Smtp [smtp server name] 121 | 122 | Specify the port to use with the SMTP server with -Port [port number]. 123 | If none is specified then the default of 25 will be used. 124 | 125 | Specify the user to access SMTP with -User [example@contoso.com] 126 | Specify the password file to use with -Pwd [path\]ps-script-pwd.txt. 127 | Use SSL for SMTP server connection with -UseSsl. 128 | 129 | To generate an encrypted password file run the following commands 130 | on the computer and the user that will run the script: 131 | " 132 | Write-Host -Object ' $creds = Get-Credential 133 | $creds.Password | ConvertFrom-SecureString | Set-Content [path\]ps-script-pwd.txt' 134 | } 135 | 136 | else { 137 | ## If logging is configured, start logging. 138 | ## If the log file already exists, clear it. 139 | If ($LogPathUsr) 140 | { 141 | ## Clean User entered string 142 | $LogPath = $LogPathUsr.trimend('\') 143 | 144 | ## Make sure the log directory exists. 145 | If ((Test-Path -Path $LogPath) -eq $False) 146 | { 147 | New-Item $LogPath -ItemType Directory -Force | Out-Null 148 | } 149 | 150 | $LogFile = ("On-Prem-AD-User-Creator_{0:yyyy-MM-dd_HH-mm-ss}.log" -f (Get-Date)) 151 | $Log = "$LogPath\$LogFile" 152 | 153 | If (Test-Path -Path $Log) 154 | { 155 | Clear-Content -Path $Log 156 | } 157 | } 158 | 159 | ## Function to get date in specific format. 160 | Function Get-DateFormat 161 | { 162 | Get-Date -Format "yyyy-MM-dd HH:mm:ss" 163 | } 164 | 165 | ## Function for logging. 166 | Function Write-Log($Type, $Evt) 167 | { 168 | If ($Type -eq "Info") 169 | { 170 | If ($LogPathUsr) 171 | { 172 | Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [INFO] $Evt" 173 | } 174 | 175 | Write-Host -Object "$(Get-DateFormat) [INFO] $Evt" 176 | } 177 | 178 | If ($Type -eq "Succ") 179 | { 180 | If ($LogPathUsr) 181 | { 182 | Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [SUCCESS] $Evt" 183 | } 184 | 185 | Write-Host -ForegroundColor Green -Object "$(Get-DateFormat) [SUCCESS] $Evt" 186 | } 187 | 188 | If ($Type -eq "Err") 189 | { 190 | If ($LogPathUsr) 191 | { 192 | Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [ERROR] $Evt" 193 | } 194 | 195 | Write-Host -ForegroundColor Red -BackgroundColor Black -Object "$(Get-DateFormat) [ERROR] $Evt" 196 | } 197 | 198 | If ($Type -eq "Conf") 199 | { 200 | If ($LogPathUsr) 201 | { 202 | Add-Content -Path $Log -Encoding ASCII -Value "$Evt" 203 | } 204 | 205 | Write-Host -ForegroundColor Cyan -Object "$Evt" 206 | } 207 | } 208 | 209 | ## Function for Update Check 210 | Function UpdateCheck() 211 | { 212 | $ScriptVersion = "23.04.28" 213 | $RawSource = "https://raw.githubusercontent.com/Digressive/On-Prem-AD-User-Creator-Utility/master/On-Prem-AD-User-Creator.ps1" 214 | 215 | try { 216 | $SourceCheck = Invoke-RestMethod -uri "$RawSource" 217 | $VerCheck = $SourceCheck -split '\n' | Select-String -Pattern ".VERSION $ScriptVersion" -SimpleMatch -CaseSensitive -Quiet 218 | 219 | If ($VerCheck -ne $True) 220 | { 221 | Write-Log -Type Conf -Evt "*** There is an update available. ***" 222 | } 223 | } 224 | 225 | catch { 226 | } 227 | } 228 | 229 | ## Check for required options 230 | If ($Null -eq $UsersList) 231 | { 232 | Write-Log -Type Err -Evt "You must specify a users list with -CSV" 233 | Exit 234 | } 235 | 236 | If ($Null -eq $HomeDrive -And $HomeUncUsr) 237 | { 238 | Write-Log -Type Err -Evt "You need to set both -HomeLetter and -HomePath" 239 | Exit 240 | } 241 | 242 | If ($Null -eq $HomeUncUsr -And $HomeDrive) 243 | { 244 | Write-Log -Type Err -Evt "You need to set both -HomeLetter and -HomePath" 245 | Exit 246 | } 247 | 248 | # Set variables for options not set 249 | If ($Null -eq $OrgUnit) 250 | { 251 | $OrgUnit = 'CN=Computers,DC=contoso,DC=com' 252 | } 253 | 254 | If ($Null -eq $AdUpn) 255 | { 256 | $AdUpn = Get-addomain | Select-Object Forest -ExpandProperty Forest 257 | } 258 | 259 | If ($HomeUncUsr) 260 | { 261 | $HomeUnc = $HomeUncUsr.trimend('\') 262 | } 263 | 264 | If ($Null -eq $LogPathUsr -And $SmtpServer) 265 | { 266 | Write-Log -Type Err -Evt "You must specify -L [path\] to use the email log function." 267 | Exit 268 | } 269 | 270 | ## getting Windows Version info 271 | $OSVMaj = [environment]::OSVersion.Version | Select-Object -expand major 272 | $OSVMin = [environment]::OSVersion.Version | Select-Object -expand minor 273 | $OSVBui = [environment]::OSVersion.Version | Select-Object -expand build 274 | $OSV = "$OSVMaj" + "." + "$OSVMin" + "." + "$OSVBui" 275 | 276 | ## 277 | ## Display the current config and log if configured. 278 | ## 279 | Write-Log -Type Conf -Evt "--- Running with the following config ---" 280 | Write-Log -Type Conf -Evt "Utility Version: 23.04.28" 281 | Write-Log -Type Conf -Evt "Hostname: $Env:ComputerName." 282 | Write-Log -Type Conf -Evt "Windows Version: $OSV." 283 | 284 | If ($UsersList) 285 | { 286 | Write-Log -Type Conf -Evt "CSV file: $UsersList." 287 | } 288 | 289 | If ($OrgUnit) 290 | { 291 | Write-Log -Type Conf -Evt "OU for users: $OrgUnit." 292 | } 293 | 294 | If ($AdUpn) 295 | { 296 | Write-Log -Type Conf -Evt "User UPN: $AdUpn." 297 | } 298 | 299 | If ($HomeDrive) 300 | { 301 | Write-Log -Type Conf -Evt "Home Letter: $HomeDrive." 302 | } 303 | 304 | If ($HomeUncUsr) 305 | { 306 | Write-Log -Type Conf -Evt "Home UNC Path: $HomeUncUsr." 307 | } 308 | 309 | If ($AdGrps) 310 | { 311 | Write-Log -Type Conf -Evt "Groups to add user to:" 312 | 313 | ForEach ($Grp in $AdGrps) 314 | { 315 | Write-Log -Type Conf -Evt " $Grp" 316 | } 317 | } 318 | 319 | If ($LogPathUsr) 320 | { 321 | Write-Log -Type Conf -Evt "Logs directory: $LogPath." 322 | } 323 | 324 | If ($Null -ne $LogHistory) 325 | { 326 | Write-Log -Type Conf -Evt "Logs to keep: $LogHistory days." 327 | } 328 | 329 | If ($MailTo) 330 | { 331 | Write-Log -Type Conf -Evt "E-mail log to: $MailTo." 332 | } 333 | 334 | If ($MailFrom) 335 | { 336 | Write-Log -Type Conf -Evt "E-mail log from: $MailFrom." 337 | } 338 | 339 | If ($MailSubject) 340 | { 341 | Write-Log -Type Conf -Evt "E-mail subject: $MailSubject." 342 | } 343 | 344 | If ($SmtpServer) 345 | { 346 | Write-Log -Type Conf -Evt "SMTP server: Configured." 347 | } 348 | 349 | If ($SmtpUser) 350 | { 351 | Write-Log -Type Conf -Evt "SMTP auth: Configured." 352 | } 353 | 354 | Write-Log -Type Conf -Evt "---" 355 | Write-Log -Type Info -Evt "Process started" 356 | ## 357 | ## Display current config ends here. 358 | ## 359 | 360 | If ($Null -ne $UsersList) 361 | { 362 | If (Test-Path -Path $UsersList) 363 | { 364 | ## Use this for password generation 365 | Add-Type -AssemblyName System.Web 366 | 367 | #Creating array for the sam account names for use later 368 | $SamsList = @() 369 | 370 | #Get the users names from the CSV 371 | $UserCsv = Import-Csv -Path $UsersList 372 | 373 | ForEach ($User in $UserCsv) { 374 | ## Clean ' from first names 375 | $FirstnameClean = $User.Firstname -replace "[']" 376 | 377 | ## If firstname is long, shorten for samaccountname limit + rand number 378 | $NameSafeLen = $FirstnameClean.substring(0, [System.Math]::Min(16, $FirstnameClean.Length)) 379 | 380 | # Create a random number 381 | $RandNum = (Get-Random -Minimum 0 -Maximum 9999).ToString('0000') 382 | 383 | $SamName = $NameSafeLen + $RandNum 384 | $SamsList += $SamName 385 | $UserFirstName = $User.Firstname 386 | $UserLastName = $User.Lastname 387 | $UserFullName = $UserFirstName + " " + $UserLastName 388 | 389 | ## The UPN set as the new sam account name and the email domain. 390 | $Upn = $SamName + "@$AdUpn" 391 | $DisplayName = $UserFullName 392 | $Pwrd = ([System.Web.Security.Membership]::GeneratePassword(8,0)) 393 | 394 | ## If no home letter or path is configured, set to null 395 | If ($HomeUncUsr) 396 | { 397 | $HomeUncFull = "$HomeUnc\$SamName" 398 | } 399 | 400 | else { 401 | $HomeUncFull = $null 402 | $HomeDrive = $null 403 | } 404 | 405 | ## Check for existance of existing users with same name 406 | $UserExist = Get-ADUser -filter "SamAccountName -eq '$SamName'" 407 | 408 | ## If a user does already exist with name sam name, regenerate the nummber and try to create again. Do this until user does not exist. 409 | do { 410 | # Create a random number 411 | $RandNum = (Get-Random -Minimum 0 -Maximum 9999).ToString('0000') 412 | $UserExist = Get-ADUser -filter "SamAccountName -eq '$SamName'" 413 | 414 | try { 415 | New-ADUser -Name "$SamName" -GivenName "$UserFirstName" -Surname "$UserLastName" -DisplayName "$DisplayName" -SamAccountName $SamName -UserPrincipalName $Upn -Path $OrgUnit -AccountPassword (ConvertTo-SecureString $Pwrd -AsPlainText -Force) -ChangePasswordAtLogon $true -Enabled $true -HomeDirectory $HomeUncFull -HomeDrive $HomeDrive 416 | Write-Log -Type Info -Evt "(User) Creating new user $UserFirstName $UserLastName - Username: $SamName, Password: $Pwrd [END]" 417 | } 418 | 419 | catch { 420 | Write-Log -Type Err -Evt $_.Exception.Message 421 | } 422 | 423 | } until ($null -eq $UserExist) 424 | } 425 | 426 | ## If Groups are configured, find and add them 427 | If ($AdGrps) 428 | { 429 | ForEach ($Sams in $SamsList) { 430 | ForEach ($AdGrp in $AdGrps) { 431 | try { 432 | Add-ADGroupMember -Identity $AdGrp -Members $Sams 433 | Write-Log -Type Info -Evt "(Group) Adding user: $Sams to $AdGrp" 434 | } 435 | catch { 436 | Write-Log -Type Err -Evt $_.Exception.Message 437 | } 438 | } 439 | } 440 | } 441 | 442 | ## Jobs done. 443 | Write-Log -Type Info -Evt "Process finished" 444 | } 445 | 446 | else { 447 | Write-Log -Type Err -Evt "The specified file was not found." 448 | } 449 | } 450 | 451 | else { 452 | Write-Log -Type Err -Evt "No csv file specified." 453 | } 454 | 455 | If ($Null -ne $LogHistory) 456 | { 457 | ## Cleanup logs. 458 | Write-Log -Type Info -Evt "Deleting logs older than: $LogHistory days" 459 | Get-ChildItem -Path "$LogPath\On-Prem-AD-User-Creator_*" -File | Where-Object CreationTime -lt (Get-Date).AddDays(-$LogHistory) | Remove-Item -Recurse 460 | } 461 | 462 | ## This whole block is for e-mail, if it is configured. 463 | If ($SmtpServer) 464 | { 465 | If (Test-Path -Path $Log) 466 | { 467 | ## Default e-mail subject if none is configured. 468 | If ($Null -eq $MailSubject) 469 | { 470 | $MailSubject = "On-Prem AD User Creator Utility Log" 471 | } 472 | 473 | ## Default Smtp Port if none is configured. 474 | If ($Null -eq $SmtpPort) 475 | { 476 | $SmtpPort = "25" 477 | } 478 | 479 | ## Setting the contents of the log to be the e-mail body. 480 | $MailBody = Get-Content -Path $Log | Out-String 481 | 482 | ForEach ($MailAddress in $MailTo) 483 | { 484 | ## If an smtp password is configured, get the username and password together for authentication. 485 | ## If an smtp password is not provided then send the e-mail without authentication and obviously no SSL. 486 | If ($SmtpPwd) 487 | { 488 | $SmtpPwdEncrypt = Get-Content $SmtpPwd | ConvertTo-SecureString 489 | $SmtpCreds = New-Object System.Management.Automation.PSCredential -ArgumentList ($SmtpUser, $SmtpPwdEncrypt) 490 | 491 | ## If -ssl switch is used, send the email with SSL. 492 | ## If it isn't then don't use SSL, but still authenticate with the credentials. 493 | If ($UseSsl) 494 | { 495 | Send-MailMessage -To $MailAddress -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Port $SmtpPort -UseSsl -Credential $SmtpCreds 496 | } 497 | 498 | else { 499 | Send-MailMessage -To $MailAddress -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Port $SmtpPort -Credential $SmtpCreds 500 | } 501 | } 502 | 503 | else { 504 | Send-MailMessage -To $MailAddress -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Port $SmtpPort 505 | } 506 | } 507 | } 508 | 509 | else { 510 | Write-Host -ForegroundColor Red -BackgroundColor Black -Object "There's no log file to email." 511 | } 512 | } 513 | ## End of Email block 514 | } 515 | ## End --------------------------------------------------------------------------------