How to Use RunWithElevatedPrivileges in PowerShell Scripts for SharePoint?

We use RunWithElevatedPrivileges method to impersonate System Account (Application pool identity), which is granted with FULL control access rights via web application user policy. Here is an example of using RunwithElevatedPrivileges with PowerShell:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
[Microsoft.SharePoint.SPSecurity]::RunWithElevatedPrivileges(
{

    #Define the parameter values: Site collection URL and user account to remove
    $siteURL =  "https://sharepoint.crescent.com/sites/sales"
    $userAccount = "crescent\Salaudeen" 
  
    #Get the RootWeb
    $web= Get-SPWeb $siteURL
    #Get the user acount - If doesn't exists ADD
    $user = $web.EnsureUser($userAccount)
 
    #Make the user as Site collection Admin
    $user.IsSiteAdmin = $true
    $user.Update()
 
    #Print a message
    Write-host "User: $($userAccount) has been added as site collection administrator!"   
 
 }
)  

This PowerShell example uses run with elevated privileges in SharePoint to add new site collection administrator.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *