PowerShell to remove SharePoint Users from a Group

PowerShell to remove SharePoint Users from a Group

Many time you have to remove multiple users from the SharePoint group. Doing this through the GUI Interface will be time consuming. A PowerShell script to remove users from the SharePoint group will definitely help in this scenario.

Approach

1 . List down email of all the users in a Notepad file and save it with .CSV extension. I named this file as Email_Listing.csv

CSV files containing all Email

2. Open the PowerShell ISE editor to run the below code

# Check if SharePoint PowerShell Library is loaded
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
    Write-Host "Connect Sharepoint Cmd-Let"
    Add-PSSnapin Microsoft.SharePoint.PowerShell 
}
# Load the location of CSV file and import it
$CSVFileLoc = "C:\Powershell_Scripts\Users_List_NGEMRDoc_Training.csv"
$CSVFile = Import-CSV $CSVFileLoc -Header "Email"

#Provide the site location
$SiteURL = "https://hisextvpapp02/sites/testsite /"
#Provide the name of Sharepoint group
$grpName = "NGEMR Read Only"
#Get the Web
$web=Get-SPWeb $SiteURL           
#Get the Group by its name
$Group = $Web.sitegroups | Where-Object {$_.Name -eq $grpName} 
if($Group -ne $null)
{
foreach($CSVUser in $CSVFile)
              {
                try
                 { 
                   #check if the user exist, if user doesnot exist it will
	           # through an exception handeld by the Catch block
                   $spUser = $Group.Users.GetByEmail($CSVUser.Email)
                   $Group.RemoveUser($spUser)
                   write-host "User : $($CSVUser) removed from the Group" 
                 }
                catch
                {
                    #User Not found
                    #write-host $_.Exception.Message
                    write-host "User : $($CSVUser) not found inside the group" -ForegroundColor Red
                }

            }
         }
         else
         {
            write-host "Group: $($GroupName) was not found in the Site" -ForegroundColor Red
         }

With small modification you can modify this script to add multiple users inside the group. So instead of $Group.RemoveUser() we can change this to $Group.AddUser()

Leave a Reply

avatar