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:
