ELM-ADTools.psm1
Function Export-Users { Param( [int]$Days ) # end param # Get path friendly date (dd-mm-yy) $Today = Get-Date -UFormat %d-%m-%y # Get ALL users in domain $AllUsers = Get-ADUser -filter * -Properties * # Filter uses only if Days variable has been assigned if ($Days) { # Filter to those logged in within last 90 days $AllUsers = $AllUsers | Where-Object lastlogondate -gt ((Get-Date).AddDays(-$Days)) } # Output to a CSV file with firstname, lastname, username, and also OU they were in $AllUsers | Select-Object givenname, surname, samaccountname, distinguishedname | ConvertTo-Csv -NoTypeInformation | Out-File -FilePath "$Home\Desktop\User_Export-$Today.csv" } function Export-UserList { param ( [Parameter(Mandatory=$true)] [string]$Group ) # Put all members of group in to a variable $GroupMembers = Get-ADGroupMember -Identity $Group # Prepare a blank array $UsersToList = @() # As Get-ADGroupMember does not return the "description" field we will need to loop through and Get-ADUser on each group member to get all their properties Foreach ($User in $GroupMembers) { # Set the current value in the pipe line to $User $_ = $User # Get the ADUser using their account name $User = Get-ADUser -Filter {samaccountname -eq $_.SamAccountName -and enabled -eq $true} -Properties * # Add them to the emtpy array created earlier $UsersToList += $User } # Sort by description and then by name # Put in a table and group by description # If they are a student then change the group heading to "Year Group" from "Description" # Else assume they are staff and change the group heading to "Role" from "Description" # Change property name (SamAccountName to Username) # Output to a text file on the desktop If ($Group -like "Student*") { $UsersToList | Sort-Object @{expression=”Description”;Ascending=$true}, @{expression=”Name”;Ascending=$true} | Format-Table -AutoSize -GroupBy @{Name="Year Group";Expression='Description'} -Property ` @{Label="Name";Expression={$_.Name}}, @{Label="Username";Expression={$_.SamAccountName}} | Out-File "$HOME\Desktop\$Group User List.txt" } else { $UsersToList | Sort-Object @{expression=”Description”;Ascending=$true}, @{expression=”Name”;Ascending=$true} | Format-Table -AutoSize -GroupBy @{Name="Role";Expression='Description'} -Property ` @{Label="Name";Expression={$_.Name}}, @{Label="Username";Expression={$_.SamAccountName}} | Out-File "$HOME\Desktop\$Group User List.txt" } } function Set-CorrectDisplayNames { param ( [string]$OU ) # get users in a certain OU $allusers = Get-ADUser -Filter * -SearchBase $OU # loop through all users found foreach($user in $allusers){ # assign variables $firstname = $user.givenname $surname = $user.surname $olddisplayname =$user.name # reassign variables with correct capitalization $firstname = $firstname.substring(0,1).ToUpper()+$firstname.substring(1).ToLower() $surname = $surname.substring(0,1).ToUpper()+$surname.substring(1).ToLower() # create the correct displayname $newdisplayname = $firstname + " $surname" # perform the rename action Set-ADUser -Identity $user -DisplayName $newdisplayname Rename-ADObject -Identity $user -NewName $newdisplayname Write-Host "Renamed $olddisplayname to $newdisplayname" -ForegroundColor Green } } Function Import-Users { <# .<help keyword> <help content> #> #Requires -RunAsAdministrator [cmdletbinding(SupportsShouldProcess=$True)] Param( [Parameter(Mandatory=$true)] [string]$csv, [Parameter(Mandatory=$true)] [ValidateSet('johnd','john.d','jdoe','j.doe','john.doe')] [string]$UsernameFormat, [Parameter(Mandatory=$true)] [ValidateSet('Staff','Office','Students')] [string]$UserType, [Parameter(Mandatory=$true)] [string]$HomeShare, [Parameter(Mandatory=$true)] [string]$ProfileShare, $Password, $LogPath = "$env:USERPROFILE\Desktop\User Import Logs" ) # Set log file and delete it if it already exists # Gets todays date in a readable, sortable format (yyyy-mm-dd) $Date = Get-Date -UFormat "%Y%m%d_%H%M%S" $LogFile = "$LogPath\user import log $Date.csv" # Store the data from the CSV in the $Users variable $Users = Import-csv $csv # Defines what the CSV headers should be $CorrectHeaders = @( 'firstname' 'lastname' 'description' ) # Assigns the actual headers to a variable $ImportHeaders = (($Users[0].psobject.properties.name)) # Counts the differencnes $HeaderDiffs = (Compare-Object $CorrectHeaders $ImportHeaders).count # Throws an error if the differences are not 0 if ($HeaderDiffs -ne '0') { Throw "Check your CSV Headers! Should be 'firstname,lastname,description'" } # Set some Variables $Domain = (Get-ADDomain).name $FullDomain = (Get-ADDomain).dnsroot $DomainRoot = (Get-ADDomain).DistinguishedName $HomePath = "$HomeShare\$UserType" $ProfilePath = "$ProfileShare\$UserType" $bar = "*" * 125 # Tests for an "Imported Users" OU at root of domain and if it does not exist then it creates it $ImportOU = "OU=Imported Users,$DomainRoot" try { Get-ADOrganizationalUnit -Identity $ImportOU | Out-Null } catch { New-ADOrganizationalUnit -Name "Imported Users" -Path $DomainRoot } # Check Home & Profile paths exist if (!(Test-Path $HomePath)) { Throw "Could not find $HomePath!" } if (!(Test-Path $ProfilePath)) { Throw "Could not find $ProfilePath!" } # Loop through each row containing user details in the CSV file foreach ($User in $Users) { # Read user data from each field in each row and assign the data to a variable as below $Firstname = $User.firstname $Lastname = $User.lastname $FullName = "$Firstname $Lastname" $Description = $User.description # Select username format if ($UsernameFormat -eq "johnd") { $Username = $Firstname + $Lastname.substring(0,1) } if ($UsernameFormat -eq "john.d") { $Username = $Firstname + "." + $Lastname.substring(0,1) } if ($UsernameFormat -eq "jdoe") { $Username = $Firstname.substring(0,1) + $Lastname } if ($UsernameFormat -eq "j.doe") { $Username = $Firstname.substring(0,1) + "." + $Lastname } if ($UsernameFormat -eq "john.doe") { $Username = $Firstname + "." + $Lastname } # change to lower case and remove - and ' $Username = $Username.ToLower() $Username = $Username.Replace('-','').replace("'",'') # Check username doesn't already exist in AD and if it does take first 2 letters of firstname #while (Get-ADUser -Filter {SamAccountName -eq $Username}) { # $Username = $Firstname.substring(0,2) + $Lastname # } # Generate a random password and make the first letter a capital if ($Password -eq $null) { # get a random password $Password = Invoke-WebRequest "http://www.dinopass.com/password/simple" -Verbose:$False | Select-Object Content -ExpandProperty Content # capitalize first letter $Password = (Get-Culture).TextInfo.ToTitleCase($Password) } $PasswordSecure = $Password | ConvertTo-SecureString -AsPlainText -Force # Create splat of user params $UserParams = @{ SamAccountName = $Username UserPrincipalName = "$Username@$FullDomain" Name = $FullName GivenName = $Firstname Surname = $Lastname Enabled = $True DisplayName = $FullName Path = $ImportOU ProfilePath = "$ProfilePath\$Username" HomeDrive = "H:" HomeDirectory = "$HomePath\$Username" Description = $Description AccountPassword = $PasswordSecure ChangePasswordAtLogon = $true } # Create an object to make reporting later easier $UserObject = [PSCustomObject]@{ FirstName = $Firstname LastName = $Lastname UserName = $Username Description = $Description Password = $Password } # Export users to CSV File if (!(Test-Path $LogFile)) { $UserObject | ConvertTo-Csv -NoTypeInformation | Out-File -FilePath $LogFile -Append -Force }else{ # Skip CSV headers if file already exists $UserObject | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File -FilePath $LogFile -Append -Force } Write-Verbose "Attempting to create $FullName with username $Username and Password $Password" New-ADUser @UserParams Write-Verbose "Creating home directory: $HomePath\$Username" # Create users home folder and give them full rights New-Item -Name $Username -Path $HomePath -ItemType Directory | Out-Null Write-Verbose "Setting access rights..." $Acl = Get-Acl "$HomePath\$Username" $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("$Domain\$Username","FullControl","ContainerInherit,ObjectInherit","None","Allow") $Acl.SetAccessRule($Ar) Set-Acl "$HomePath\$Username" $Acl Write-Verbose "Assigning to groups..." # Add them to AD groups Add-ADGroupMember -Identity $UserType -Members $Username # Set password again after group membership (fine grained password policy) if ($($UserType) -eq "Students") { Write-Verbose "Setting a simple password..." Set-ADAccountPassword -Identity $Username -Reset -NewPassword $PasswordSecure Set-ADUser -Identity $Username -CannotChangePassword $true -ChangePasswordAtLogon $false -PasswordNeverExpires $true -Enabled $true } Write-Verbose "Moving on to next user..." Write-Verbose $bar } } |