Wednesday, June 2, 2021

PowerShell Script - Get the size of the Sites

 I have tested this script on SharePoint 2013 to get the size of the sub-sites with in a Site Collection.


#Get Size of all Sub-sites in a Site Collection
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
# Function to calculate folder size
Function CalculateFolderSize($Folder)
{
    [long]$FolderSize = 0
    foreach ($File in $Folder.Files)
    {
        #Get File Size
        $FolderSize += $file.TotalLength;
        #Get the Versions Size
        foreach ($FileVersion in $File.Versions)
        {
            $FolderSize += $FileVersion.Size
        }
    }

    #Iterate through all subfolders
    foreach ($SubFolder in $Folder.SubFolders)
    {
        #Call the function recursively
        $FolderSize += CalculateFolderSize $SubFolder
    }

    return $FolderSize
}

$SiteURL = "http://MySPSite/sites/portal"
$Site = new-object Microsoft.SharePoint.SPSite($SiteURL)
foreach($Web in $Site.AllWebs)
{ 
    #Call function to calculate Folder Size
    [long]$WebSize = CalculateFolderSize($Web.RootFolder)
    #Get Recycle Bin Size
    foreach($RecycleBinItem in $Web.RecycleBin)
    {
        $WebSize += $RecycleBinItem.Size
    }
    $Size = [Math]::Round($WebSize/1MB, 2)
    Write-Host $web.Url ":`t" $Size "MB"
}

Expected Output:

Find and Delete Orphaned Users in SharePoint

 Orphaned User? Who are they?

Orphaned users are those who have been disabled/removed from Active Directory, but still have permissions to sites, lists and items. Internally, SharePoint keeps them in "UserInfo" table of the content database for meta-data such as created/modified by fields.
how to delete orphaned users in sharepoint

Its unavoidable in any organization where employees constantly on-boarding and off-boarding. Its really difficult to manage, when it comes to thousands of sub-sites, sites, libraries and lists with their own sets of permissions.

SharePoint doesn't automatically remove users when they are deleted or disabled in Active directory!
Why we care about Orphaned users?
It is a best practice to delete orphaned users to keep the farm clean & organized. Also this will solve the problem of deleted active directory users still appearing on the people picker which was discussed here  People Picker not showing users from Active Directory? . If you know the user base or criteria then you can use: Clean-up User Information List

Found only few users and want to delete them?
Go to: http://YOUR-SHAREPOINT-SITE-URL/_layouts/people.aspx?MembershipGroupId=0
This will give the master list of users in site collection, from here you can remove users who are no longer need by clicking "Remove Users from Site Collection"

If you know the orphaned user name (E.g. Employee left the Company), You can go to above URL Filter and delete the particular user. Alternatively, You can query the SQL Server table to find the orphaned users.  Here is how:

Step 1. Open SQL Server Management Studio from SharePoint's SQL box, and run this query for relevant content database.

SELECT * FROM [MOSS_Content_DatabaseName].[dbo].[UserInfo] WHERE tp_Login='DOMAIN\UserID'

Step 2. Take note of the tp_ID column value

Step 3. Go to http://<your sharepoint-site-collection/_layouts/userdisp.aspx?ID=tp_ID, where tp_ID is the number you found from the above select statement.

Step 4. This will take you to the user's profile where you can click on the Delete User from Site Collection button.

However, it is not possible to manually check for SharePoint 2010 orphaned users and clean them, as it would take lot of time. Things become easier with PowerShell, Lets use it here to find & delete Orphaned users in SharePoint.

Ref: Find and Delete Orphaned Users in SharePoint - SharePoint Diary

How to Find and Delete Orphaned Users in SharePoint using PowerShell
Here is my script to Find and Delete Orphaned SharePoint Domain Users: Find and Delete Orphaned Users in SharePoint with PowerShell
Related Post: Remove all alerts assigned to Orphaned users: Find and Delete Orphaned Alerts in SharePoint

 Find and Delete Orphaned Users in SharePoint with PowerShell

Orphaned Users in SharePoint. in short, SharePoint orphaned users are those who are deleted from Active Directory, but still have permissions to SharePoint sites!  Read more here: Find and Delete Orphaned Users in SharePoint
find and delete orphaned users in sharepoint

PowerShell to Find and Delete Orphaned Users in SharePoint
Now, with PowerShell, We can Find and Delete orphaned users in SharePoint. Here is the script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Parameter
$WebAppURL="http://intranet.crescent.com"
  
#Function to Check if a User exists in AD
Function Check-UserExistsInAD()
{
    Param( [Parameter(Mandatory=$true)] [string]$UserLoginID)
    Write-host $UserLoginID
    #Search the User in AD
    $Forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
    foreach ($Domain in $forest.Domains)
    {
        $context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain", $Domain.Name)
        $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($context)
     
        $root = $domain.GetDirectoryEntry()
        $search = [System.DirectoryServices.DirectorySearcher]$root
        $search.Filter = "(&(objectCategory=User)(samAccountName=$UserLoginID))"
        $result = $search.FindOne()
  
        if ($result -ne $null)
        {
           return $true
        }
    }
  return $false 
 }
   
#Get all Site Collections of the web application
$WebApp = Get-SPWebApplication $WebAppURL
  
#Iterate through all Site Collections
Foreach($site in $WebApp.Sites) 
{
    #Get all Webs with Unique Permissions - Which includes Root Webs
    $WebsColl = $site.AllWebs | Where {$_.HasUniqueRoleAssignments -eq $True} | ForEach-Object {        
    $OrphanedUsers = @()        
    #Iterate through the users collection
    ForEach($User in $_.SiteUsers)
    {
        #Exclude Built-in User Accounts , Security Groups
        if(($User.LoginName.ToLower() -ne "nt authority\authenticated users") -and
            ($User.LoginName.ToLower() -ne "sharepoint\system") -and
                ($User.LoginName.ToLower() -ne "nt authority\local service"-and
                    ($user.IsDomainGroup -eq $false ) )
                {
                    $UserName = $User.LoginName.split("\")  #Domain\UserName
                    $AccountName = $UserName[1]    #UserName
                    if ( ( Check-UserExistsInAD $AccountName) -eq $false )
                    {
                                Write-Host "$($User.Name)($($User.LoginName)) from $($_.URL) doesn't Exists in AD!"
                                      
                                #Make a note of the Orphaned user
                                $OrphanedUsers+=$User.LoginName
                    }
                }
        }
    }
}
         
# ****  Remove Users ****#
# Remove the Orphaned Users from the site
# foreach($OrpUser in $OrphanedUsers)
#   {
#        $_.SiteUsers.Remove($OrpUser)
#        Write-host "Removed the Orphaned user $($OrpUser) from $($_.URL) "
#   }



Executing this script will scan and give the list of orphaned users in a SharePoint web application. It can be used in SharePoint 2010 also to find & delete orphaned users.

SharePoint orphaned users cleanup:
I've commented out the "Remove Users" section at the bottom of the script.  Just remove # tags to un-comment and execute the script to delete orphaned users in SharePoint.