Pages

Monday, August 19, 2013

Accessing SharePoint User Profiles using PowerShell commands


This post will help you access the user profiles stored within your User Profile Service Application. It is applicable to both SharePoint 2010 as well SharePoint 2013.

Load the SharePoint snap-in into your management shell -

$snapinName = "Microsoft.SharePoint.PowerShell"
if ((Get-PSSnapin | Where-Object {$_.Name -eq $snapinName }) -eq $NULL)
{
  write-host "SharePoint SnapIn not loaded. Loading..."
  Add-PSSnapin $snapinName -ErrorAction SilentlyContinue
}

Create the SPService Context used to initialize the Profile Manager instance -

$proxyGroup = Get-SPServiceApplicationProxyGroup -default
$subId = [Microsoft.SharePoint.SPSiteSubscriptionIdentifier]::Default
$context = [Microsoft.SharePoint.SPServiceContext]::GetContext($proxyGroup, $subId)

Initialize the ProfileManager object using the created Context object -

$ProfileManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)

Using this object, create an Enum type object to iterate / enumerate through all the user profiles -

$Profiles = $ProfileManager.GetEnumerator()

Now, there are two ways to loop through these profiles -

1. Using foreach loop

foreach($profile in $Profiles)
{
$property1 = $profile["<Property_Name>"].Value
$property2 = $profile["<Property_Name>"].Value
}

Above, <Property_Name> denotes the name of any user profile property you have created or is available out-of-the-box.

2. Using while loop

while($Profiles.MoveNext())
{
$profile = $Profiles.Current
                $property1 = $profile["<Property_Name>"].Value
$property2 = $profile["<Property_Name>"].Value
}


If you wish to save or export the profile data into a CSV file, you can modify your code above to something like below -

Using foreach loop approach -

Get the location of the file which should save your data -

$propertiesFileName = "\UPA-Profiles.csv"
$outputFile = (Get-Location -PSProvider FileSystem).ProviderPath + $propertiesFileName

Create a Collection which would every single row of your CSV file -

$collection = @()

Then, the loop -

foreach($profile in $Profiles)
{
$profileData = "" | select "Property1","Property2","Property3"
$profileData.Property1= $profile["<Property_Name>"].Value
$profileData.Property2= $profile["<Property_Name>"].Value
$profileData.Property3= $profile["<Property_Name>"].Value
$collection += $profileData
}
$collection | Export-Csv $outputFile -NoTypeInformation


Hope this helps ...




No comments:

Post a Comment