Wednesday, June 2, 2021

 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.

Wednesday, March 17, 2021

 

How to export URL rewrite rules.


Wehave 2 options to export the rewrite rules:


1) We can look in the web.config file, and copy the <rewrite> section, then paste into the web.config file on the new system.

Or,

2) We can use appcmd to export the rules to a file, and to import them on the new system:


App command location: cd %windir%\system32\inetsrv


Export:

appcmd list config "websitename/appname" -section:system.webServer/rewrite/rules -xml > rewriterules.xml


Import (globaly on the server):

appcmd set config -in < rewriterules.xml

Import for a specific website:

 appcmd set config "testWebsite\" -in < rewriterules.xml

You can also export any global rewrite rules using:

appcmd list config -section:system.webServer/rewrite/globalRules -xml > globalrewriterules.xml

The import command would be the same.

Wednesday, January 27, 2021

How to Make an O365 SharePoint Online site collection read-only and inaccessible

 Introduction 

 
This blog talks about how a site collection in O365 can be made read-only or inaccessible. It also discusses how when the site collection is inaccessible, you can redirect the users to an information page.
 
Problem Statement 
 
We were recently working on a project in which we needed to do a tenant-to-tenant migration. As a part of the migration process, we wanted to make the source site collection ready after the migration and then after 2 weeks' time, make it inaccessible. When the site collection was inaccessible, we also wanted to redirect the user to a page that would have an explanation of why they were unable to access the site.
 
Solution 
 
The ability to make a site read-only or inaccessible is provided by the lockstate property of the Set-SPOSite powershell command.
 
Read Only 
 
In order to make a site read-only, we have to execute the command:
 
Set-SPOSite https://[tenant].sharepoint.com/sites/targetsite -LockState ReadOnly
 
Inaccessible 
 
In order to make a site inaccessible, we have to execute the command:
 
Set-SPOSite https://[tenant].sharepoint.com/sites/targetsite -LockState NoAccess
 
When the site is set to NoAccess, the business users will be shown a standard 403 forbidden page.
 
Redirection 
 
To make this user-friendly, there may be a need to inform the business users as to why they are unable to open the site.
 
This can be achieved by including the parameter  "NoAccessRedirectUrl" along with the URL in the PS command.
 
Set-SPOTenant -NoAccessRedirectUrl 'https://www.contoso.com'
 
Note: As this URL is set at the Tenant level, every SPO site and ODFB site that has been marked as NoAccess will be redirected to the 1 above URL, hence the URL to which the users are redirected should contain information addressing both of them.
 
Unlock 
 
In order to make a site accessible and editable by end-users, we have to execute the command:
 
Set-SPOSite https://[tenant].sharepoint.com/sites/targetsite -LockState Unlock
 
CSOM
 
While we have seen the powershell commands, this can also be executed through CSOM 
  1. using (var clientContext = new ClientContext(tenantUrl))  
  2. {  
  3.       clientContext.Credentials = spoCredentials;  
  4.       var tenant = new Tenant(clientContext);  
  5.       var siteProperties = tenant.GetSitePropertiesByUrl(siteUrl, true);  
  6.       clientContext.Load(siteProperties);  
  7.       clientContext.ExecuteQuery();  
  8.       Console.WriteLine("LockState: {0}", siteProperties.LockState);  
  9.       siteProperties.LockState = "Unlock";  
  10.       siteProperties.Update();  
  11.       clientContext.ExecuteQuery();  
  12. }

Ref: https://www.c-sharpcorner.com/blogs/make-an-o365-sharepoint-online-site-collection-read-only-and-inaccessible#:~:text=The%20ability%20to%20make%20a,the%20Set%2DSPOSite%20powershell%20command.&text=When%20the%20site%20is%20set,a%20standard%20403%20forbidden%20page.