Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Tuesday, November 4, 2014

PowerShell Script to remove all permissions for SharePoint user

Threw this powershell script together to wipe out a user from your farm...I have this running in conjunction with other scripts that disable the user in active directory.


Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
[Void][Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$claimsPrefix = "[Prefix for the user you're removing from the farm]"
$site = New-Object Microsoft.SharePoint.SPSite("[a site]");
$service = Get-SPServiceContext $site;
$site.Dispose();

$upm = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($service);

$user = Get-ADUser -Identity [THE USER]

#I use email as the identity in my farm, thus this line

$mail = Get-ADUser $user -Properties mail | Select -ExpandedProperty mail
$profile = $upm.GetUserProfile($claimsPrefix+$mail);

#Delete MySite

Remove-SPSite $profile.PersonalSite -Confirm:$false;

#Delete Profile

$upm.RemoveUserProfile($claimsPrefix+$mail);

$webApps = Get-SPWebApplication -IncludeCentralAdministration
foreach ($webApp in $webApps){

    #Remove explicit rights given in web application policies
    $webApp.Policies.Remove($claimsPrefix+$mail);

    $siteCollections = Get-SPSite -WebApplication $webApp -Limit All

    foreach($site in $siteCollections){
        $spuser = Get-SPuser -Web $site.RootWeb -Identity $claimsPrefix+$mail;

        #Remove from site collection admins
        $site.RootWeb.SiteAdministrators.Remove($spuser);
        foreach($web in $site.AllWebs){
            $spuser = Get-SPUser -Web $web -Identity  $claimsPrefix+$mail;
            foreach($group in $web.Groups){
                
                #Remove from all groups in website
                $group.RemoveUser($spuser);
            }
            if ($web.HasUniqueRoleAssignments -eq $true){

                #Remove any explicit role assignments
                $web.RoleAssignments.Remove($spuser);
            }
            foreach($list in $web){
                if ($list.HasUniqueRoleAssignments -eq $true){

                    #Remove any explicit list role assignments
                    $list.RoleAssignments.Remove($spuser); 
                }#list
            }#lists
        }#webs
    }#sites
}#webapps