Wednesday 25 June 2014

Script Creating SharePoint User MySites using PowerShell

While working on a large migration project (SharePoint 2010 to SharePoint 2013), I had a requirement to script the creation of user MySites for hundreds of users. I knocked this little PowerShell function together to do just that!

Function Create-MySite            
{            
 [CmdletBinding()]            
 Param            
 (            
  [Parameter(Mandatory = $True,Position=2,valueFromPipeline=$true)][String]$Username,            
     [Parameter(Mandatory = $True,Position=1)][String]$MySiteRootURL              
 )            
 [void][reflection.assembly]::Loadwithpartialname("Microsoft.Office.Server");               
 $site=new-object Microsoft.SharePoint.SPSite($MySiteRootURL);            
 try            
 {            
  $serviceContext = Get-SPServiceContext $site;            
  $upm = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceContext);             
  if($upm.UserExists($Username) -eq $false)            
  {            
   Write-Host "User $Username was not found in the profile store." -f yellow;            
   return;            
  }            
  $userProfile = $upm.GetUserProfile($Username);            
  if($userProfile.PersonalSite -eq $Null)            
  {            
   Write-Host "Creating MySite for user $Username" -f darkyellow;            
   $userProfile.CreatePersonalSite();                  
   Write-host "Successfully created MySite for user $Username" -f green;            
  }            
  else            
  {            
   Write-Host "User $Username already has a MySite." -f darkgreen;            
  }            
 }            
 catch            
 {            
  Write-Host "Encountered an error creating a MySite for user $Username. Error:"$_.Exception -f Red;            
 }            
 finally            
 {            
  $site.Dispose();            
 }            
}

You can call the function like this (for a single user):

#Example - Create a MySite for user  "tonyj"            
Create-MySite -MySiteRootURL "http://mysite.bigintranet.com.au" -Username "tonyj"

Or call it like this, for a batch of users:

#To Create for an array of users            
$users = @('tonyj','bobh','markf','billd')            
$users | Foreach {Create-MySite -MySiteRootURL "http://mysite.bigintranet.com.au" -username $_}

No comments:

Post a Comment