Active Directory XML Import

This script is designed to import users saved in an XML document file into Active Directory. The XML document should have the following fields or layout, though it can process as many <user> fields in an XML as you need:

<root>
     <user>
          <account>ashepard</account>
          <firstname>Alan</firstname>
          <lastname>Shepard</lastname>
          <description>Commander</description>
          <password>password1234</password>
          <manager></manager>
          <ou>Spectre</ou>
          <memberOf>
               <group>Spectre</group>
               <group>N7</group>
               <group>Systems Alliance Navy</group>
          </memberOf>
     </user>
</root>

PowerShell Script:

Param([Parameter(Mandatory=$True)][string]$filepath)
$x = [xml](get-content -Path $filepath)

### PULL THE OUs AND CREATE FROM XML
$OU = $x.root.user.ou|group|foreach{$_.Name}
foreach($ItemOU in $OU){
 try{
 new-ADOrganizationalUnit -name $ItemOU
 "OU $ItemOU created"
 }
 catch{"The OU $ItemOU already exists"}
}

"----------OU Creation Complete----------"

### PULL THE GROUPS AND CREATE VIA XML
$Group = $x.root.user.memberOf.group|group|foreach{$_.Name}
foreach($ItemGroup in $Group){
 try{
 new-ADGroup -name $ItemGroup -GroupScope universal
 "Group $ItemGroup created"
 }
 catch{"The Group $ItemGroup already exists"}
}

"--------Group Creation Complete---------"

### CREATE USERS
$users = $x.root.user
foreach($user in $users){
 try{
### CREATE USER
 New-ADUser -Name $user.account -GivenName $user.firstname -Surname $user.lastname -Description $user.description -AccountPassword (ConvertTo-SecureString $user.password -AsPlainText -Force) -Path "OU=$($user.ou),$(Get-ADDomain | select -ExpandProperty DistinguishedName)" –Enabled $True -ChangePasswordAtLogon $True
 "User $($user.account) created"

### ADD USER TO GROUP
 $UserGroup = $user.memberOf.group
 foreach($MemberOf in $UserGroup){
 Add-ADGroupMember $MemberOf $user.account
 "$($user.account) added to $MemberOf"
 } 
 }
 catch{"The user $($user.account) already exists"}
}

"---------User Creation Complete---------"

## ADD THE MANAGER FOR EACH CREATED USER
foreach($user in $users){
 try{
 Set-ADUser $user.account -manager $user.manager
 "Manager $($user.manager) added for $($user.account)"
 }catch{"The user $($user.account) is already managed by $($user.manager)"}
}
"-------Manager Additions Complete-------"
"---------XML Document Processed---------"