Quantcast
Channel: Gav's Blog – SharePoint .NET & Tech
Viewing all articles
Browse latest Browse all 41

Extracting a full list of users from SharePoint

$
0
0

I had an interesting ask from a customer the other day.
“Can I get a report of all the users in the system along with some key pieces of data that is stored on their user profile?”
Sure there are probably a bunch of other ways to do this, search springs to mind. But for this customer the best thing I could give them was a csv file so they could generate some reports and charts from this information. So once again it’s PowerShell to the rescue.

A few things to note about this script, first and foremost the user account executing it MUST have rights to connect to the User Profile Service Application. If they don’t you get a lovely error message which doesn’t make a lot of sense:

New-Object : Exception calling ".ctor" with "1" argument(s): "Object reference not set to an instance of an object."
 + $upa = new-object <<<<  ("Microsoft.Office.Server.UserProfiles.UserProfileManager") $context 
 + CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
 + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

If you do have to grant your account permissions to the User Profile Service Application it is necessary to A) restart the service on the server and B) get a fresh PowerShell instance in order for this change to get picked up.This version gets every user profile in your UPA, if you’re after certain people either use .Search() or do some filtering inside the enumeration loop.

Add-PSSnapIn Microsoft.Sharepoint.Powershell
$site = Get-SPSite <a href="http://mysiteurl">http://mysiteurl</a>
$context = Get-SPServiceContext $site
$upa = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
$enumer = $upa.GetEnumerator()
$enumer.Reset()
while($enumer.MoveNext()){
     $user = $enumer.Current
     $row = $user.RecordId.ToString() + ", " + $user.AccountName  + ", " + $user.DisplayName+ ", " + $user["PropertyOfInterest1"]
     write-output $row
}

According to the docs for IEnumerator on MSDN MoveNext() will return false when it moves beoynd the bounds of the collection being enumerated and Reset() followed by MoveNext() should be used to set the Current item to the first item in the collection.I’ve used Write-Output in this case because I can easily combine this with Output-File to create csv output files like so:

.\ReadUsers.ps1 | Output-File .\UserDump.csv

Filed under: PowerShell, SharePoint Tagged: PowerShell, SharePoint, User Profiles

Viewing all articles
Browse latest Browse all 41

Trending Articles