donderdag 27 november 2014

List assigned right for a site collection

A quick way to find out the rights assigned to a site collection.

static void Main(string[] args)
{
    using (SPSite site = new SPSite(args[0]))
    {
        foreach (SPWeb web in site.AllWebs)
        {
            try
            {
                if (web.HasUniqueRoleAssignments)
                {
                    Console.WriteLine(web.ServerRelativeUrl);
                    var col = web.RoleAssignments;
                    foreach (SPRoleAssignment item in col)
                    {
                        string[] roles = item.RoleDefinitionBindings.Cast<SPRoleDefinition>().Where(b => b.Name != "Beperkte toegang").Select(b => b.Name).ToArray();

                        if (roles.Length > 0)
                        {
                            if (item.Member is SPGroup)
                            {
                                SPGroup g = (SPGroup)item.Member;
                                if (g.Users.Count > 0)
                                    {
                                    Console.WriteLine("Groep: {0} - Role(s): {1} ({2} members)",
                                        item.Member.LoginName,
                                        string.Join(", ", roles),
                                        g.Users.Count);
                                }
                            }
                            else
                            {
                                SPUser user = (SPUser)item.Member;
                                if (!user.IsSiteAdmin)
                                {
                                    Console.WriteLine("User: {0} - Role(s): {1}",
                                        item.Member.LoginName,
                                        string.Join(", ", roles));
                                }
                            }
                        }
                    }
                    Console.WriteLine();
                }
            }
            finally
            {
                web.Dispose();

            }

        }
    }
}
Note. Roles "Beperkte toegang", Dutch name for the role "Limited access" is filtered out, and users that are SiteCollection administrators are excluded from the results to create a more readable result.