Thursday 7 April 2016

Create user profile from AD using powershell

Hi,

After a long time. Coming to straight point, how do we create user profiles automatically for those AD users available.

Case : During one of the implementation of my project I came through one scenario in which I need to get all AD users and iterate through it. Check if user profile exists for that AD user or not? If not create user profile for it. I am pasting my script here. Please find below powershell script :

import-module activedirectory
$users = Get-ADUser -Filter * -SearchBase "OU=TESTGroup,DC=YOURADFOREST,DC=COM"

$spsite = new-object Microsoft.SharePoint.SPSite(<YOUR MY SITE HOST URL>)
$context = [Microsoft.Office.Server.ServerContext]::GetContext($spsite)
$pmanager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)

ForEach($user in $users)  
{    
   Write-Output('' + $user.UserPrincipalName)
   $exists = $pmanager.UserExists($user.UserPrincipalName)
   if ($exists -eq $false)
   {
     Write-Output('Profile for this user is not created...')
     $pmanager.CreateUserProfile($user.UserPrincipalName)
     $up = $pmanager.GetUserProfile($user.UserPrincipalName)
     $up.CreatePersonalSite()
   }
}

Note: Prior to execute this script do test Get-ADUser, if it throws any error then you need to install AD feature. To do so you can use these 2 commands

Import-Module ServerManager

Add-WindowsFeature RSAT-AD-PowerShell

In above given code snippet

OU=TESTGroup, TESTGroup is group name.
DC=YOURADFOREST YOURADFOREST is your forest name

That's it from my side. Hope this helps needy one. Thanks.

No comments:

Post a Comment