HisSmartHome.BulkADUser.psm1
function Add-BulkUserHSM { <# .SYNOPSIS Bulk create Active Directory user accounts from a CSV file. .DESCRIPTION Expects a CSV with the following columns: First Name, Last Name, Display Name, Username, Password, OrgUnit, Email, Description, Pager .PARAMETER CsvPath Path to the CSV file. .PARAMETER WhatIfOnly Run in test mode — validates the CSV and OUs, but does not create any accounts. .EXAMPLE Add-BulkUserHSM -CsvPath "C:\Temp\users.csv" .EXAMPLE Add-BulkUserHSM -CsvPath "C:\Temp\users.csv" -WhatIfOnly #> [CmdletBinding()] param( [Parameter(Mandatory = $true)] [ValidateScript({ Test-Path $_ })] [string]$CsvPath, [switch]$WhatIfOnly ) Import-Module ActiveDirectory -ErrorAction Stop $users = Import-Csv -Path $CsvPath foreach ($user in $users) { try { # Validate OU if (-not (Get-ADOrganizationalUnit -LDAPFilter "(distinguishedName=$($user.OrgUnit))" -ErrorAction SilentlyContinue)) { Write-Warning "Skipping $($user.'Display Name') - OU not found: $($user.OrgUnit)" continue } $securePassword = ConvertTo-SecureString $user.Password -AsPlainText -Force # Build custom attributes (Pager must be handled here) $attributes = @{} if ($user.Pager -and $user.Pager.Trim() -ne '') { $attributes['pager'] = $user.Pager } if ($WhatIfOnly) { Write-Host "Would create user: $($user.'Display Name') in $($user.OrgUnit)" -ForegroundColor Cyan } else { New-ADUser ` -GivenName $user.'First Name' ` -Surname $user.'Last Name' ` -DisplayName $user.'Display Name' ` -SamAccountName $user.Username ` -UserPrincipalName ("{0}@{1}" -f $user.Username, (Get-ADDomain).DnsRoot) ` -EmailAddress $user.Email ` -Description $user.Description ` -AccountPassword $securePassword ` -Path $user.OrgUnit ` -Enabled $true ` -ChangePasswordAtLogon $true ` -OtherAttributes $attributes Write-Host "Created user: $($user.'Display Name')" -ForegroundColor Green } } catch { Write-Error "Failed to create user: $($user.'Display Name'). Error: $_" } } } function Get-BulkTemplateHSM { <# .SYNOPSIS Downloads the Bulk AD User CSV template. .DESCRIPTION Retrieves the template CSV from https://cdn.hsho.me/BulkAD/Template.csv and saves it to the specified destination path. .PARAMETER DestinationPath Full path (including filename) where the CSV template will be saved. .EXAMPLE Get-BulkTemplateHSM -DestinationPath "C:\Temp\Template.csv" #> [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$DestinationPath ) $url = "https://cdn.hsho.me/BulkAD/Template.csv" try { Invoke-WebRequest -Uri $url -OutFile $DestinationPath -UseBasicParsing Write-Host "Template downloaded to $DestinationPath" -ForegroundColor Green } catch { Write-Error "Failed to download template: $_" } } |