X

New Active Directory User and Office365 New User Powershell Procedure

As a systems administrator, quite often you’ll need to create new user accounts in Active Directory and MSOnline Office 365. It’s good to streamline your new user creation procedure as much as possible to make the process faster and more accurate. Thanks to PowerShell, we can turn a whole bunch of point and clicks into just a few PowerShell commands. In this example procedure we will first create an Active Directory AD user account with powershell and a .csv file and then add that user into multiple groups with a different powershell script and a .txt file that has a list of the groups. We will also use another powershell script to get the canonical name of the groups so that our script can find the LDAP location of the group in Active Directory. Secondly, because we do not run our own exchange server we will use powershell to connect to Office365, and create a new user there, license the user, and then add the user to some distribution groups. Prerequisites are powershell, and import AD components and MSOnline components.

  1. Go to https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Create-Active-7e6a3978 and download the create_ad_users.zip and extract to c:\newusers\
  2. Edit create_ad_users.ps1 lines 92 and 98 to accommodate longer last names. In the original script it only allows for first initial and then a truncated last name of 4 characters. In my case, we have some users with long last names, so I set those values to 20:
  3. If($replace.length -lt 20)
    {
      $lastname = $replace
    }
    Else
    {
      $lastname = $replace.substring(0,20)
    }
    
  4. Copy info from your HR department about the new user into the .csv file c:\newusers\import_create_ad_users.csv
  5. Run PS C:\newusers> .\create_ad_users.ps1
  6. Next check the new username in ADUC for such things as account name, address, phone number etc. to ensure the entries are accurate.
  7. With our new user account created, most likely we will want to make that user a member of several security groups. To do that with PowerShell, we need to make sure that we have the correct LDAP names for our groups and place them into a file named groups.txt. In order to do so, we need to run another powershell script named find-dn.ps1 . The code is as follows:
    # Function Find Distinguished Name
    function find-dn { param([string]$adfindtype, [string]$cName)
        # Create A New ADSI Call
        $root = [ADSI]''
        # Create a New DirectorySearcher Object
        $searcher = new-object System.DirectoryServices.DirectorySearcher($root)
        # Set the filter to search for a specific CNAME
        $searcher.filter = "(&(objectClass=$adfindtype) (CN=$cName))"
        # Set results in $adfind variable
        $adfind = $searcher.findall()
        
        # If Search has Multiple Answers 
        if ($adfind.count -gt 1) {
            $count = 0 
            foreach($i in $adfind)
            {
                # Write Answers On Screen
                write-host $count ": " $i.path
                $count += 1
            }
            # Prompt User For Selection
            $selection = Read-Host "Please select item: "
            # Return the Selection
            return $adfind[$selection].path
        }
        # Return The Answer
        return $adfind[0].path
    }

    This code should be inserted into a new PowerShell ISE tab and then saved as find-dn.ps1 . Running the code will produce a new PowerShell function (but will not write any output to the screen.) Find the group names in ADUC that you want the CN name for, and then use the following command(s) to return the CN name:

    find-dn "group" "FinanceGroup"

    The script will return something similar to the following:

    LDAP://CN=FinanceGroup,CN=Users,DC=intranet,DC=contoso,DC=com

    Remove the part “LDAP://” and copy the remaining string into the c:\newusers\groups.txt file, which after finding the rest of your group CN names, should look something similar to the following:

    CN=FinanceGroup,CN=Users,DC=intranet,DC=contoso,DC=com
    CN=HRGroup,CN=Users,DC=intranet,DC=contoso,DC=com
    CN=OperationsGroup,CN=Users,DC=intranet,DC=contoso,DC=com
    CN=ITGroup,CN=Users,DC=intranet,DC=contoso,DC=com
    CN=AccountingGroup,CN=Users,DC=intranet,DC=contoso,DC=com
    CN=ComplianceGroup,CN=Users,DC=intranet,DC=contoso,DC=com
    CN=MarketingGroup,CN=Users,DC=intranet,DC=contoso,DC=com
  8. Now that we have our CN security group names, we can add the user(s) into the groups with the following script. For this step we can utilize the script found here: https://community.spiceworks.com/topic/459481-adding-users-to-multiple-security-groups-in-ad – which was contributed by Martin9700 . Copy the following script into a new PowerShell ISE tab and name the file Add-MultipleGroups.ps1 :
    #requires -Version 3.0
    Param (
        [Parameter(Mandatory,ValueFromPipeline)]
        [String[]]$Groups,
        [Parameter(Mandatory)]
        [String[]]$Users,
        [switch]$Passthru
    )
    
    Begin {
        Try { Import-Module ActiveDirectory -ErrorAction Stop }
        Catch { Write-Error "Unable to load Active Directory module, is RSAT installed?"; Exit }
        $Result = @()
    }
    
    Process {
        ForEach ($Group in $Groups)
        {   Try {
                Add-ADGroupMember $Group -Members $Users -ErrorAction Stop
                $Result += [PSCustomObject]@{
                    Group = $Group
                    AddMembers = $Users -join ", "
                }
            }
            Catch {
                Write-Error "Error adding members to $Group because $($Error[0])"
                $Result += [PSCustomObject]@{
                    Group = $Group
                    AddMembers = $Error[0]
                }
            }
        }
    }
    
    End {
        If ($Passthru)
        {   $Result
        }
    }
  9. Run the following command to add user to the appropriate security groups:
PS C:\newusers> .\Add-MultipleGroups.ps1 -Groups "CN=ITGroup,CN=Users,DC=intranet,DC=contoso,DC=com","CN=OperationsGroup,CN=Users,DC=intranet,DC=contoso,DC=com" -users user1, user2

With the above script you can use the file to run a number of different options as well such as:

You can just put the group names in -Groups:

.\Add-MultipleGroups.ps1 -Groups "testgroup1","testgroup2" -users user1,user2,user3,user4

You can use a text file (either in Groups or via pipeline):

.\Add-MultipleGroups.ps1 -Groups (Get-content c:\groups.txt) -users user1,user2,user3,user4

Get-content c:\groups.txt | .\Add-MultipleGroups.ps1 -Groups -users user1,user2,user3,user4

You can also use Get-Content for users, but you can pipe it:

Get-content c:\groups.txt | .\Add-MultipleGroups.ps1 -Groups -users (Get-content c:\users.txt)

You can confirm in ADUC that the users are now members of the security groups in our groups.txt file.

Add users to Office 365 and Distribution Groups with PowerShell

Great! Now that we have our user accounts created on the AD side of things, we will move on to adding our user(s) into Office365:

With PowerShell up and running will will issue the following commands:

From https://www.petri.com/use-powershell-create-assign-licenses-office-365-users

Import-Module MSOnline

Connect-MsolService

Now we will create the user with the following command:

New-MsolUser -UserPrincipalName user1@contoso.com -DisplayName ‘User 1’ -FirstName User -LastName 1

This command will return something like the following (sorry about the formatting:)

PS C:\Users\jcoltrin> New-MsolUser -UserPrincipalName user1@contoso.com -DisplayName ‘User 1’ -FirstName User -LastName 1



Password                                   UserPrincipalName                          DisplayName                                isLicensed

--------                                   -----------------                          -----------                                ----------

Suso4007                                   user1@contoso.com                       User 1                                False

Now we need to add a license to the user account. We need to do two things before we can assign the licenses. First is we need to to determine the different sku’s we have available to license, and second, we need to set the usage location. To accomplish the first part, we can issue the command:

Get-MsolAccountSku

Second, by using the instructions here: https://social.technet.microsoft.com/Forums/ie/en-US/bfde2a73-579c-409b-a7cd-77110048c7b7/license-enabling-script?forum=onlineservicesadministrationcenter

We can set the MS Online user’s principal location:

Set-MsolUser -UserPrincipalName user1@contoso.com -UsageLocation US


Set-MsolUserLicense -UserPrincipalName user1@contoso.com -AddLicenses Contoso:STANDARDPACK

Now that the user is licensed, we will add the account to a few Exchange Distribution Groups. We will need to import a new PSSession from outlook.com before we can run the Exchange commands. Import the session by first creating a function called “Connect-O365” by running the following (just like we created the function find-dn above):

function Connect-O365{
 $o365cred = Get-Credential username@domain.onmicrosoft.com
 $session365 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell/" -Credential $o365cred -Authentication Basic -AllowRedirection 
 Import-Module (Import-PSSession $session365 -AllowClobber) -Global
}

Save and name this function: Connect-O365.ps1 and run it. We now have a function that we can run:

.\Connect-O365.ps1
Connect-O365

(enter creds)

Now we can add the distribution group members with the group identity and member name in quotes:

Add-DistributionGroupMember -Identity "Finance" -Member "user1@contoso.com"

Add-DistributionGroupMember -Identity "AllEmployees" -Member "user1@contoso.com"

A number of these scripts and commands can be combined into .ps1 files to optimize the workflow even further. With the information here you should have a good place to start. Let me know in the comments how you added your own features to the procedure.

coltrinit:
Related Post