PowerShell Scripts



Let see some of the most useful PowerShell commands in SharePoint to perform below activities.

Read SMTP Outgoing Mail Address from Central Administration
Get/Set Primary and Secondary Site Administrator
Remove user from Site Collection Admin
Remove user from Site Groups
Set user from direct web Roles Permissions


Read SMTP Outgoing Mail Address from CA

function LoadEmailConfig()
{
    try
    {   
        $caWebApp = (Get-SPWebApplication -IncludeCentralAdministration) | ? { $_.IsAdministrationWebApplication -eq $true } 
        Write-Host("SmtpServer: " + $caWebApp.OutboundMailServiceInstance.Server.Address)
        Write-Host("FromAdress: " + $caWebApp.OutboundMailSenderAddress)
    }
    catch
    {
        WriteToLog ("Trying to get eMail Configuration from Central Admin. Exception:- " + $_.exception.message)
    }


Get/Set Primary/Secondary Site Administrator

function GetAdmins()
{
    $site = Get-SPSite "https://site.domain.com/sites/sitecollection"
    Write-Host("Primary Site Admin:   " + $site.Owner)
    Write-Host("Secondary Site Admin: " + $site.SecondaryContact)
}

function SetAdmins()
{
    $RootSite = Get-SPWebApplication "https://site.domain.com"
    $newAdminUser = $RootSite.Sites[0].RootWeb.EnsureUser("domain\rathanavel")

    foreach($site in $RootSite.Sites)
    {
        if($site.Owner.UserLogin.Split('\\')[1] -eq "ratsub")
        {
            Write-Host("User found in Primary Site Admin: " + $site.Owner.UserLogin)

            try
            {
                Set-SPSite -Identity $site -OwnerAlias $newAdminUser
                Write-Host("New Primary Site administration configured.")
            }
            catch
            {
                Write-Host([String]::Format("Unable to change Primary Site Admin from {0} to {1}: {2}", $site.Owner.UserLogin , $fallbackUser.LoginName, $_.Exception.Message))
            }
        }

        if($site.SecondaryContact.UserLogin.Split('\\')[1] -eq "ratsub")
        {
            Write-Host("User found in Secondary Site Admin: " + $site.SecondaryContact.UserLogin)

            try
            {
                Set-SPSite -Identity $site -SecondaryOwnerAlias $newAdminUser
                Write-Host("New Secondary Site administration configured.")            
            }
            catch
            {
                Write-Host([String]::Format("Unable to change Secondary Site Admin from {0} to {1}: {2}", $site.SecondaryContact.UserLogin , $fallbackUser.UserLogin, $_.Exception.Message))
            }
        }
    }
}


Remove user from Site Collection Admin:

function CheckAndRemoveSiteCollectionAdmin
{
    $RootSite = Get-SPWebApplication "https://site.domain.com"
    #$userToRemove = $RootSite.Sites[0].RootWeb.EnsureUser("domain\ratsub")
    $userToRemove = "ratsub@domain.com"

    foreach($site in $RootSite.Sites)
    {
        $admIds = New-Object System.Collections.ArrayList
        
        #Check in Site collection admins
        foreach($siteAdmin in $site.RootWeb.SiteAdministrators)
        {
            try
            {
                #if($siteAdmin.UserLogin.Split('\\')[1] -eq $userToRemove.UserLogin.Split('\\')[1])
                if($siteAdmin.Email -eq $userToRemove.Email)
                {
                    write-host ("User found:- " + $siteAdmin.LoginName)
                    $admIds.Add($siteAdmin.ID)
                }
            }
            catch
            {
                Write-Host ("Add user to array from Site Collection Admin. Exception message:  "  +  $_.Exception.Message) 
            }
        }
        

        #Remove user from Site Collection admin if exist
        foreach($admUser in $admIds)
        {
            try
            {
                $site.RootWeb.SiteAdministrators.RemoveByID($admUser)
                Write-Host ("User removed.")
            }
            catch
            {
                Write-Host ("Remove user from Site Collection Admin. Exception message:  "  +  $_.Exception.Message) 
            }            
        }
    }
}


Remove user from Site Groups

function RemoveUserFromSiteGroups
{
    $RootSite = Get-SPWebApplication "https://site.domain.com"
    #$userToRemove = $RootSite.Sites[0].RootWeb.EnsureUser("domain\ratsub")
    $userToRemove = "ratsub@domain.com"

    foreach($site in $RootSite.Sites)
    {
        foreach($web in $site.AllWebs)
        {
            Write-Host ("Checking Web: " + $web.Url)
            try
            { 
                # Loop only if $web has boken inheritance
                if($web.HasUniqueRoleAssignments -eq $true)
                {
                    # Loop all site groups
                    foreach ($grp in $web.SiteGroups)
                    {
                        try
                        {                            
                            $lstUserIds = New-Object System.Collections.ArrayList
                
                            # Loop users to check and add to remove array if user exist
                            foreach ($user in $grp.Users) 
                            {
                                try
                                {                        
                                    if($user.Email -eq $userToRemove.Email)
                                    {                            
                                        $lstUserIds.Add($user.ID)
                                        Write-Host ("User found in group : " + $user.LoginName + " | " + $grp.Name)
                                    }
                                }
                                catch
                                {
                                     Write-Host ("Exception inside AllWeb->Web->GroupLoop->Add user id in array. Error message: "  +  $_.Exception.Message)
                                } 
                            }

                            # Remove array users from group
                            foreach($id in $lstUserIds)
                            {
                                try
                                {
                                    $usr = $grp.Users | ? { $_.ID -eq $id } 
                                    $userDeleted = $usr.UserLogin
                    
                                    $grp.Users.RemoveByID($id)

                                    write-host ("Removed User From Group:- User: " + $userDeleted + "|| Group:" + $grp.Name)
                                }
                                catch
                                {
                                     Write-Host ("Exception inside AllWeb->Web->GroupLoop->Remove user from group. Error message: " + $_.Exception.Message)
                                }
                            }
                        }
                        catch
                        {
                             Write-Host ("Exception in foreach Group loop: " + $_.Exception.Message)
                        }
                    }
                }
            }
            catch
            {
                Write-Host ("Exception in AllWeb->Web loop: " + $_.Exception.Message)
            }
        }
    }
}


Set user from Direct web Roles Permissions

function RemoveUserWebRolePermissions
{
    $RootSite = Get-SPWebApplication "https://site.domain.com"
    #$userToRemove = $RootSite.Sites[0].RootWeb.EnsureUser("domain\ratsub")
    $userToRemove = "ratsub@domain.com"

    foreach($site in $RootSite.Sites)
    {
        foreach($web in $site.AllWebs)
        {
            Write-Host ("Checking Web: " + $web.Url)
            try
            {
                # Loop direct web Role assignments permissions
                $lstIds = New-Object System.Collections.ArrayList
                foreach($role in $web.RoleAssignments)
                {
                    try
                    {                                               
                        if($role.Member.GetType().ToString() -eq "Microsoft.SharePoint.SPUser")
                        {
                            if($role.Member.Email -eq $userToRemove.Email)
                            {
                                $lstIds.Add($role.Member.ID)
                                Write-Host ("User found in web RoleAssignments:- User: " + $role.Member.LoginName + " || Url: " + $web.Url)                               
                            }
                        }
                    }
                    catch
                    {
                        Write-Host ("Exception in foreach loop RoleAssignments->Add id in array: " + $_.Exception.Message)
                    }
                }

                # Remove users from current role
                foreach($id in $lstIds)
                {
                    try
                    {
                        $usr = $web.RoleAssignments | ? { $_.Member.ID -eq $id }                 
                        $userDeleted = $usr.Member.Name
                        
                        $web.RoleAssignments.RemoveByID($id);

                        write-host ("Deleted User Permissions From Web:- User: " + $userDeleted + " || Url: " + $web.Url)                   
                        
                    }
                    catch
                    {
                        Write-Host("Exception in foreach loop RoleAssignments->Remove user from role assignments: " + $_.Exception.Message)
                    }
                }
            }
            catch
            {
                Write-Host ("Exception in AllWeb->Web loop: " + $_.Exception.Message)
            }
        }
    }
}

Will see more commands and scenarios in the upcoming series.

Related Articles:

-Ratsub

Comments

Popular posts from this blog

Secure When a HTTP request is received Power Automate a.k.a MS Flow

People picker Control in PowerApps

Upload attachment to SharePoint list item using Microsoft Flow

Approval and auto escalation with time out in Microsoft Flow

Modern page provisioning using page template

Headless-Daemon calling AAD secured API

Developing custom reusable components in PowerApps

Step-By-Step Azure AD App Registration

HTML field & Date Time formatting in powerapps

Create and configure custom connectors for PowerApps and MSFlow from AzureFunctions