SharePoint Online: PowerShell to Remove User from All Sites

Requirement: Remove User from All Sites in SharePoint Online
SharePoint Online Delete User from All Sites using PowerShell

PowerShell to Remove a User from All SharePoint Online Site Collections:
The following PowerShell script will remove the provided login account from all Site collections of your SharePoint Online. Please note, you must be a site collection administrator for all site collections before running this script. 
#Config Parameters
$AdminSiteURL="https://crescent-admin.sharepoint.com"
$UserAccount = "[email protected]"
 
#Connect to SharePoint Online Tenant Admin
Connect-SPOService -URL $AdminSiteURL -Credential (Get-Credential)
 
#Get all Site Collections
$SitesCollections = Get-SPOSite -Limit ALL

#Iterate through each site collection
ForEach($Site in $SitesCollections)
{
    Write-host -f Yellow "Checking Site Collection:"$Site.URL
 
    #Get the user from site collection
    $User = Get-SPOUser -Limit All –Site $Site.URL | Where {$_.LoginName -eq $UserAccount}
 
    #Remove the User from site collection
    If($User)
    {
        #Remove the user from the site collection
        Remove-SPOUser -Site $Site.URL –LoginName $UserAccount
        Write-host -f Green "`tUser $($UserAccount) has been removed from Site collection!"
    }
}

Delete a User from All SharePoint Online Sites using PnP PowerShell
Here is the PnP PowerShell to delete user from all sites
#Parameters
$TenantURL =  "https://crescent.sharepoint.com"
$UserID="i:0#.f|membership|[email protected]"

#Get Credentials to connect
$Credential = Get-Credential

#Frame Tenant Admin URL from Tenant URL
$TenantAdminURL = $TenantURL.Insert($TenantURL.IndexOf("."),"-admin")
#Connect to PnP Online
Connect-PnPOnline -Url $TenantAdminURL -Credentials $Credential

#Get All Site collections - Filter BOT and MySite Host
$Sites = Get-PnPTenantSite -Filter "Url -like '$TenantURL'"

#Iterate through all sites
$Sites | ForEach-Object { 
    Write-host "Searching in Site Collection:"$_.URL -f Yellow
    #Connect to each site collection
    $SiteConn = Connect-PnPOnline -Url $_.URL -Credentials $Credential -ReturnConnection
    If((Get-PnPUser | Where {$_.LoginName -eq $UserID}) -ne $NULL)
    {
        #Remove user from site collection
        Remove-PnPUser -Identity $UserID -Confirm:$false
        Write-host "`tRemoved the User from Site:"$_.URL -f Green
    }
    Disconnect-PnPOnline -Connection $SiteConn
} 
This PnP PowerShell removes the user from all SharePoint Online sites in the tenant.

Related Posts:

2 comments:

Please Login and comment to get your questions answered!

Powered by Blogger.