Replace UMRA with Powershell Script

Issue:

Powershell has more flexibility and power than UMRA.  UMRA is expensive as you get more users.  Switching over to powershell is easy once you have a workable example.  You could take this example and combine it with the Office 365 licensing example from a previous post and get a complete user setup in one powershell script.  You could take this script and make a user interface form with powershell, READ-HOST values from the command line, or import a csv with a loop to mass create users.

You can fine tune the script to create users for every job title and department at your organization.

Solution:

#Create a User
Import-Module ActiveDirectory



#Editable Variables
$domain = "contoso.com"
#Connect to Local Exchange
$cred = Get-Credential -Message "Domain Credential" -UserName "admin@contoso.com"
$temporaryPassword = 'temp123!'

$externalDomain = '@contoso.org'
$exchangeURL = 'http://LOCALEXCHANGESERVER/PowerShell/'

$mailOnMicrosoftEmail = '@****.mail.onmicrosoft.com'

##CSV Import Example
##Import-Csv "C:\TEMP\newUsers.csv" | foreach-object {
##  $createHomeDirectory = [System.Convert]::ToBoolean($_.createHomeDirectory)
## $firstName = "$($_.firstName)"
## $initials = "$($_.initials)"
## $lastName= "$($_.lastName)"
## $samAccountName = "$($_.samAccountName)"

$createHomeDirectory = $True
$createLocalExchangeMailbox = $True
$setScriptPath = $True
$employeeHasMedical = $False

$firstName=''
$initials = ''
$lastName=''
$samAccountName=''
$department=''
$company=''
$jobTitle = ''
$employeeID= ''
$telephoneNumber=''


#End Editable Variables



#Default Values for Variables
#Set Default Values and Scope
$userPrincipalName=''  				#will be specified later


$displayName = "$lastName, $firstName"
$profilePath = 'C:\Profile.man'
$ExchangeDatabase = 'EXCHANGE01'    										##Different database for different departments
$ADOUPath = "CN=Users,DC=CONTOSO,DC=com"  							##Different path based on department/JobTitle
$homeDirectory = '' 		                                        ##Different home directories for admin			
#End Default Values for Variables


#Check if $samAccountName already exists?
#Determine username if it already exists. user our algorithm for usernames to determine next potential username
	
	
#samAccountName check
$userExist1 = Get-ADUser -Filter {sAMAccountName -eq $samAccountName}
If ($userExist1 -ne $Null) 
{
	#Log failure
	WRITE-HOST "Username already exists cannot create the user: $samAccountName"
	
}
else
{
    WRITE-HOST "Username is available: $samAccountName"
	#samAccountName is unique proceed
	if ($initials -eq "" -Or $initials -eq $Null)
	{
		$displayName="$lastName, $FirstName"
	}
	else
	{
		$displayName="$lastName, $FirstName $initials"
	}
		
	#DisplayName check
	$userExist2 = Get-ADUser -Filter {displayName -eq $displayName}
	If ($userExist2 -ne $Null) 
	{
		#Log failure
		WRITE-HOST "DisplayName already exists cannot create the user:  $displayName"
	}
	else
	{
        WRITE-HOST "DisplayName is available: $displayName"
		#displayName is unique proceed
			
		#Set Default Values for variables
		$ExchangeDatabase = 'EXCHANGE01'    									##Different database for job title
		$ADOUPath = "CN=Users,DC=CONTOSO,DC=com"  						##Different path based on department/JobTitle
		$homeDirectory = '\\FILESERVER\home\' + $samAccountName 	##Different home directories on job title
													
			
		#set defaults for departments
		switch($department)
		{
		
			"Fiscal" {
				$ExchangeDatabase = 'EXCHANGE01'    					
				$ADOUPath = 'OU=Fiscal,DC=CONTOSO,DC=com'
				$homeDirectory = '\\FILESERVER\home\' + $samAccountName
				break;
            }

			"HR" {
				$ExchangeDatabase = 'EXCHAGNE02'    					
				$ADOUPath = 'OU=Human Resources,DC=CONTOSO,DC=com'
				$homeDirectory = '\\FILESERVER\adminhome\' + $samAccountName
				break;
            }
				
			"IT" {
				$ExchangeDatabase = 'EXCHANGE03'    					
				$ADOUPath = 'OU=IT,DC=CONTOSO,DC=com'
				$homeDirectory = '\\FILESERVER\home\' + $samAccountName
				break;
			}
			
		}
			
		#set some variables by job title and department/site
		switch ($jobTitle)
		{
			"Director" {
				
				$ExchangeDatabase = 'EXCHANGE03'    					
				$homeDirectory = '\\FILESERVER\adminhome\' + $samAccountName

				switch($department)
				{
					"Fiscal" {
						$ADOUPath = 'OU=Fiscal,OU=Admin,DC=CONTOSO,DC=com'
						break;
					}	
					"HR" {
						$ADOUPath = 'OU=HR,OU=Admin,DC=CONTOSO,DC=com'
						break;
					}
				}
				break;
			}
			"Personnel Assistant" {
				
				$ExchangeDatabase = 'EXCHANGE02'    					
				$ADOUPath = 'OU=Assistants,DC=CONTOSO,DC=com'
				$homeDirectory = '\\FILESERVER2\home\' + $samAccountName
				break;
			}
				
		}
				
        
			
	    If (Test-Path $homeDirectory)
	    {
		    WRITE-HOST "Error homeDirectory already exists: $homeDirectory"
	    }
	    else
	    {
		    #homeDirectory is unique proceed
			
		    $userPrincipalName="$samAccountName" + $externalDomain
		    	
            WRITE-HOST "userPrincipalName: $userPrincipalName"
            
            WRITE-HOST "HomeDirectory: $homeDirectory"
            WRITE-HOST "ExchangeDatabase: $ExchangeDatabase"
            WRITE-HOST "ADOUPath: $ADOUPath"
                
                
		    If ($setScriptPath)
		    {
			    $scriptPath = 'SOMESCRIPT.cmd'
		    }
		    else
		    {
			    $scriptPath = ''
		    }
				
				
		    WRITE-HOST "jobTitle: $jobTitle"
            WRITE-HOST "department: $department"
            WRITE-HOST "telephoneNumber: $telephoneNumber"
            WRITE-HOST "scriptPath: $scriptPath"
                
					
		    ################### Create the User in Active Directory
		    #https://technet.microsoft.com/en-us/library/ee617215.aspx
		    #https://technet.microsoft.com/en-us/library/hh852238(v=wps.630).aspx
		    $newuser = New-ADUser -SamAccountName $samAccountName -UserPrincipalName $userPrincipalName -Name $displayName -DisplayName $displayName -GivenName $firstName -SurName $lastName -Initials $initials -Department $department -Office $department -Company $company -Description $jobTitle -Path $ADOUPath -HomeDirectory $homeDirectory -HomeDrive 'H' -ScriptPath $scriptPath -AccountPassword (ConvertTo-SecureString $temporaryPassword -AsPlainText -force) -ChangePasswordAtLogon $True -Enabled $True -PasswordNeverExpires $False -PassThru 
		    Start-Sleep -Seconds 60
            
		    if ($jobTitle)
            { 
                $newuser | SET-ADUSER -Replace @{ Title=$jobTitle }
            }
            if ($department)
            { 
                $newuser | SET-ADUSER -Replace @{ physicalDeliveryOfficeName=$department }
            }
            if ($telephoneNumber)
            {
                $newuser | SET-ADUSER -Replace @{ telephoneNumber=$telephoneNumber }
            }				
            if ($employeeID)
            {
                $newuser | SET-ADUSER -Replace @{ employeeID=$employeeID }
            }
            
		    
				
				
		    ################### Set "Remote Desktop Services Profile" tab options
		    $distinguishedName = $($newuser.distinguishedName)
		    $user = [ADSI] "LDAP://$distinguishedName"
		    $User.psbase.invokeset("TerminalServicesProfilePath",$profilePath)
		    $user.psbase.Invokeset("TerminalServicesHomeDirectory",$homeDirectory)
		    $User.psbase.invokeset("TerminalServicesHomeDrive","H:")
		    $user.setinfo()
				
				
				
		    ################### Create Home Directory
		    If ($createHomeDirectory)
		    {
			    New-Item -ItemType Directory -Path $homeDirectory
		    }
				
		    #Start Set Home Directory Permissions
		    $UsersAm = "$domain\$samAccountName" #presenting the sAMAccountname in this format 
		    #stops it displaying in Distinguished Name format 

		    #Define FileSystemAccessRights:identifies what type of access we are defining, whether it is Full Access, Read, Write, Modify

		    $FileSystemAccessRights = [System.Security.AccessControl.FileSystemRights]"FullControl"

		    #define InheritanceFlags:defines how the security propagates to child objects by default
		    #Very important - so that users have ability to create or delete files or folders 
		    #in their folders
		    $InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]::"ContainerInherit", "ObjectInherit"

		    #Define PropagationFlags: specifies which access rights are inherited from the parent folder (users folder).
		    $PropagationFlags = [System.Security.AccessControl.PropagationFlags]::None

		    #Define AccessControlType:defines if the rule created below will be an 'allow' or 'Deny' rule
		    $AccessControl =[System.Security.AccessControl.AccessControlType]::Allow 
		    #define a new access rule to apply to users folfers
				
		    $NewAccessrule = New-Object System.Security.AccessControl.FileSystemAccessRule ($UsersAm, $FileSystemAccessRights, $InheritanceFlags, $PropagationFlags, $AccessControl) 
				
		    $currentACL = Get-ACL -path	$homeDirectory
		    $currentACL.SetAccessRule($NewAccessrule)
		    Set-ACL -path $homeDirectory -AclObject $currentACL
		    #End Folder Permissions

				
		    ################## Add Groups the User
            #Groups All users need
		    Add-ADGroupMember "Some Group" $samAccountName
		    
				

            If ($employeeHasMedical)
		    {
			    Add-ADGroupMember "Medical" $samAccountName
		    }
				
		    ################# Set Additional Groups Based on JobTitle,Department
		    switch ($jobTitle)
		    {
			    "Director" {
				    Add-ADGroupMember "Director" $samAccountName
				    
				    switch($department)
				    {
					    "HR" {
						    Add-ADGroupMember "HR Director" $samAccountName
						    break;
					    }
					    "Fiscal" {
						    Add-ADGroupMember "Fiscal Director" $samAccountName
						    break;
					    }
					    
				    }
				    break;
			    }
			
			    "Personnel Assistant" {
				    Add-ADGroupMember "Assistant" $samAccountName
				    switch($department)
				    {
					    "HR" {
						    Add-ADGroupMember "HR Assistant" $samAccountName
						    break;
					    }
					    "Fiscal" {
						    Add-ADGroupMember "Fiscal Assistant" $samAccountName
						    break;
					    }
					    
				    }
				    break;
			    }
            }
        
				
		    ################## Create the Email Mailbox
		    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $exchangeURL -Authentication Kerberos -Credential $cred
		    Import-PSSession $Session
		    #local resources, but commands are run remotely
				
		    If ($createLocalExchangeMailbox)
		    {
			    Start-Sleep -Seconds 60
					
			    Enable-Mailbox -Identity $distinguishedName -Alias $samAccountName -Database $ExchangeDatabase
			    #https://technet.microsoft.com/en-us/library/bb124097(v=exchg.160).aspx
					
			    Start-Sleep -Seconds 60	
			    ################## Add Full Access Permissions to the new mailbox to a specific service user account
			    Add-MailboxPermission -Identity $distinguishedName -User voicemail_service -AccessRights FullAccess -InheritanceType All
			    
                            ##Get the email address policy to apply
                            Set-Mailbox -Identity $distinguishedName -EmailAddressPolicyEnabled $True	
		    }
		    else
		    {
			    ##set exchange properties for mailbox to be created in Office 365 quickly once licensed for Exchange Online
			    $remotemailbox = "$samAccountName" + $mailOnMicrosoftEmail
			    Enable-MailUser -Identity $samAccountName -ExternalEmailAddress $remotemailbox
			    Start-Sleep -Seconds 60
			    Set-ADUser -Identity $samAccountName Replace @{msExchHideFromAddressLists = $False; msExchRecipientDisplayType = "-2147483642"; msExchRecipientTypeDetails = "2147483648"; msExchRemoteRecipientType = "4"};
                            Start-Sleep -Seconds 30
                            ##Get the email address policy to apply                 
                            Set-RemoteMailbox -Identity $distinguishedName -EmailAddressPolicyEnabled $True
		    }
		    Remove-PSSession $Session
		    #Disconnect from local exchange
				
				
		}	
	}
}

 

Resources:

https://technet.microsoft.com/en-us/library/ee617215.aspx

https://technet.microsoft.com/en-us/library/hh852238(v=wps.630).aspx

https://technet.microsoft.com/en-us/library/bb124097(v=exchg.160).aspx

https://www.tools4ever.com/software/user-management-resource-administrator/

Leave a Reply

%d bloggers like this: