About Me

Having 12 years experience in Microsoft technologies.Since more than 7 years working in SharePoint technologies. Expert in providing consultation for SharePoint projects. Hands on with development and administration.

Monday 25 August 2014

Powershell Script - Create custom user profile properties in SharePoint 2013

The powershell script will create custom user profile properties by reading data from xml configuration file. The script accepts following input parameters

1. SiteUrl - Site colletion url
2. ManagedMetaDataServiceName - MMS service app name

Points to be noted

1. The MMS service is required, as one of the custom property gets data from predefined term set.
2. We need xml file which has required configuration.

Steps involved

1. Save following as xml file format, you can add as many as configurations you want and save as costumUserProfileProperties.xml and should be in the root directory of the script where you are running...

<?xml version="1.0" encoding="utf-8" ?>
<UserProfileProperties>
 
<Property Name="SkillSets" DisplayName="SkillSets" Type="string (Multi Value)"  IsTaxonomic="True" TermSet="Skills" Length="500" Privacy="Public" PrivacyPolicy="mandatory" IsVisibleOnEditor="$true"
IsVisibleOnViewer="$true"  IsUserEditable ="$true"></Property>

<Property Name="Interests" DisplayName="Interests" Type="string (Multi Value)"  IsTaxonomic="True" TermSet="Skills" Length="500" Privacy="Public" PrivacyPolicy="mandatory" IsVisibleOnEditor="$true"
IsVisibleOnViewer="$true"  IsUserEditable ="$true"></Property>

</UserProfileProperties>

   

2. Save following script as psCreateCustomUserProfileProperty.ps1
#-----------------------------------------------------------------------------
# Name:             psCreateCustomUserProfileProperty.ps1 
# Description:      This script will create termset names as 'Skills'
#                    and creates following user profile properties
#                   'Skills' & 'Interests'
#                    
# Usage:            Run the script by passing the paramter $SiteUrl,
#                   ManagedMetaDataServiceName
# Created By:       Vamsi Mohan Mitta
# Date:             01/07/2014
#-----------------------------------------------------------------------------

Param([Parameter(Mandatory=$true)]
      [String]
      $SiteUrl,
      [Parameter(Mandatory=$true)]
      [String]
      $ManagedMetaDataServiceName     
)

if ((gsnp Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null){
    asnp Microsoft.SharePoint.Powershell
}
#Do not modify anything in the script from here onwards
function Get-ScriptDirectory
{
 $Invocation = (Get-Variable MyInvocation -Scope 1).Value
 Split-Path $Invocation.MyCommand.Path
}

#Get Current Physical Path
$currentPhysicalPath = Get-ScriptDirectory

$logfile=$currentPhysicalPath + "\log.log"

Start-Transcript $logfile

#Connect to the Metadata Service
$taxSite = get-SPSite $SiteUrl    # Central Admin URL  
$taxonomySession = Get-SPTaxonomySession -site $taxSite
$termStore = $taxonomySession.TermStores[$ManagedMetaDataServiceName]    # Meata data service name
write-host “Connection made with term store -” $termStore.Name -ForegroundColor Green

$termGroupName = "ECTermGroup"
#Create a group
      if ($termStore.Groups[$termGroupName] -eq $null)
      {
        $termGroup = $termStore.CreateGroup($termGroupName)
        $termStore.CommitAll()
        write-host “Successfully created term group -” $termGroupName -ForegroundColor Green
      }
      else
      { write-host “Term Group already -” $termGroupName " exists" -ForegroundColor Blue }

#Connect to existing term group
$termGroup = $termstore.groups[$termGroupName];

#TERM SETS
#Create a term set

    if($termGroup.TermSets["Skills"] -eq $null)
    {
    $createTermSet = $termGroup.CreateTermSet("Skills")
    $termStore.CommitAll()
    write-host “Successfully created term set” -ForegroundColor Green
    }
    else
      { write-host “Term Set already exists" -ForegroundColor Blue }


#Connect to existing term set
$termset = $termGroup.Termsets["Skills"]

$term = $termSet.CreateTerm("Sea wall",1033)
$term.SetDescription(“Sea wall”, 1033)
$term.CreateLabel("Seawall”, 1033, $false)

$term = $termSet.CreateTerm("Tunnels and bridges",1033)
$term.SetDescription(“Tunnels and bridges”, 1033)
$term.CreateLabel("Tunnelsandbridges”, 1033, $false)


$term = $termSet.CreateTerm("Water pipelines",1033)
$term.SetDescription(“Water pipelines”, 1033)
$term.CreateLabel("Waterpipelines”, 1033, $false)

$term = $termSet.CreateTerm("Desalination plants- Land reclamation",1033)
$term.SetDescription(“Desalination plants- Land reclamation”, 1033)
$term.CreateLabel("Desalinationplants”, 1033, $false)

$TermSet.IsOpenForTermCreation = $true;

# Contribute permission on term group
$user = "c:0(.s|true"
$termGroup.AddContributor($user)


$termStore.CommitAll()

#----------------This service application is the default storage location for column specific term sets---------------------------------------------------------------


# This service application is the default storage location for column specific term sets.  on proxy peroperty select this
# Get Metadata service application proxy
$metadataserviceapplicationname = $ManagedMetaDataServiceName
Set-SPMetadataServiceApplicationProxy -Identity $metadataserviceapplicationname -DefaultSiteCollectionTaxonomy:$true

#$metadataserviceapplicationproxy = get-spmetadataserviceapplicationproxy $metadataserviceapplicationname
#$metadataserviceapplicationproxy.Properties["IsDefaultSiteCollectionTaxonomy"] = $true

# Create a custom property with above term set as input.

#----------------Get the xml file---------------------------------------------------------------

 #[xml]$xmlData=Get-Content $xmlFilePath

 $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
 $filenamne = $scriptPath + '\' + "costumUserProfileProperties.xml"
 [xml]$xmlData=Get-Content $filenamne

#----------------Create new custom User Profile properties---------------------------------------------
Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorVariable err -ErrorAction SilentlyContinue

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles")

function CreateUserProfileProperties($SiteUrl,$ManagedMetaDataServiceName)
{    
     
#Connect to the Metadata Service
$taxSite = get-SPSite $SiteUrl  
$taxonomySession = Get-SPTaxonomySession -site $taxSite
$termStore = $taxonomySession.TermStores[$ManagedMetaDataServiceName]

#Connect to existing term group
$termGroup = $termstore.groups["ECTermGroup"];
$termSetSkill = $termGroup.TermSets["Skills"]


      #$site = Get-SPSite $xmlData.UserProfileProperties.SiteURL
      $site = Get-SPSite $SiteUrl
      $context = Get-SPServiceContext($site)
      $upcm = New-Object Microsoft.Office.Server.UserProfiles.UserProfileConfigManager($context);     
      $ppm = $upcm.ProfilePropertyManager
      $cpm = $ppm.GetCoreProperties()
      $ptpm = $ppm.GetProfileTypeProperties([Microsoft.Office.Server.UserProfiles.ProfileType]::User)
      $psm = [Microsoft.Office.Server.UserProfiles.ProfileSubTypeManager]::Get($context)
      $ps = $psm.GetProfileSubtype([Microsoft.Office.Server.UserProfiles.ProfileSubtypeManager]::GetDefaultProfileName([Microsoft.Office.Server.UserProfiles.ProfileType]::User))
      $pspm = $ps.Properties
      $xmlData.UserProfileProperties.Property | ForEach-Object{
            $property = $pspm.GetPropertyByName($_.Name)         
            if($property -eq $null)
            {
                $Privacy=$_.Privacy
                $PrivacyPolicy=$_.PrivacyPolicy
                $coreProp = $cpm.Create($false)
                $coreProp.Name = $_.Name
                $coreProp.DisplayName = $_.DisplayName
                $coreProp.Type = $_.Type
                $coreProp.Length = $_.Length
                 #$coreProp.IsTaxonomic=[Microsoft.SharePoint.Taxonomy.TermSet]$_.IsTaxonomic

                 $coreProp.TermSet=$termSetSkill

                $cpm.Add($coreProp)
                $profileTypeProp = $ptpm.Create($coreProp);
                $profileTypeProp.IsVisibleOnEditor = $true;
                $profileTypeProp.IsVisibleOnViewer = $true;

                $ptpm.Add($profileTypeProp)

                $profileSubTypeProp = $pspm.Create($profileTypeProp);
                $profileSubTypeProp.DefaultPrivacy = [Microsoft.Office.Server.UserProfiles.Privacy]::$Privacy
                $profileSubTypeProp.PrivacyPolicy = [Microsoft.Office.Server.UserProfiles.PrivacyPolicy]::$PrivacyPolicy
                $profileSubTypeProp.IsUserEditable = $true;  
                $profileSubTypeProp.AllowPolicyOverride        
               
                $pspm.Add($profileSubTypeProp)
                  write-host -f yellow $_.Name property is created successfully                
            }
            else
            {
               write-host -f yellow $_.Name property already exists
            }
      }
}
#----------------Calling the function--------------------------------------------- 
 CreateUserProfileProperties -SiteUrl $SiteUrl -ManagedMetaDataServiceName $ManagedMetaDataServiceName

 Stop-Transcript
 Echo Finish


Step2: Create batch file to run the script. Save file in .bat format.

cd /d %~dp0
powershell -file  ./psCreateCustomUserProfileProperty.ps1 -SiteUrl "xxxxx" -ManagedMetaDataServiceName "MMS_Proxy"
pause

Happy powershell coding... please feel free to comment...

No comments:

Post a Comment