Second Life of a Hungarian SharePoint Geek

July 16, 2013

Accessing group permissions from PowerShell using Reflection

Filed under: PowerShell, Reflection, Security, SP 2010 — Tags: , , , — Peter Holpar @ 22:31

This time I try to give an example how to call internal and private methods of the SharePoint object model from PowerShell. Reflection is not very well documented in the context of PowerShell, however just because something is not documented does not mean that it is not possible.

Yesterday I described how to inject an SPContext into your PowerShell scripts, and recently posted a sample C# code that enables accessing group permissions from C# through Reflection. The current post is a result of combining those codes + a few tricks around PowerShell and Reflection.

WARNING: The method below is not a supported solution, it serves only learning purposes. You should not use it in a production system, in other environments use it at your own risk.

# inject fake context
$site = Get-SPSite("
http://intranet.contoso.com")
$web = $site.OpenWeb()
$request = New-Object System.Web.HttpRequest("", $web.Url, "")
$response = New-Object System.Web.HttpResponse(New-Object System.IO.StreamWriter(New-Object System.IO.MemoryStream))
$dummyContext = New-Object System.Web.HttpContext($request, $response)
$dummyContext.Items["HttpHandlerSPWeb"] = [Microsoft.SharePoint.SPWeb]$web
[System.Web.HttpContext]::Current = $dummyContext
$groupPermissions = New-Object Microsoft.SharePoint.WebControls.GroupPermissions
# set your group here
$groupId = $web.SiteGroups["Team Site Owners"].ID
$groupPermissions.GroupId = $groupId
# set dummy Page
$groupPermissions.Page = New-Object System.Web.UI.Page
# invoke private CreateDataTable method
$groupPermissionsType = $groupPermissions.GetType()
$bindingFlags = [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance
$mi_CreateDataTable = $groupPermissionsType.GetMethod("CreateDataTable", [System.Reflection.BindingFlags]($bindingFlags))
$dataTable = $mi_CreateDataTable.Invoke($groupPermissions, $null)
#process results
$regExpPattern = [regex]'<span dir="ltr">(?<scopeUrl>.*?)</span>’
$dataTable | % {
  $scopeUrl = $regExpPattern.match($_.ScopeUrl).groups[1].value
  Write-Host [$scopeUrl] [$_.Role]
}

That’s it. And the output of the run:

image

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: