Remove Sharepoint Users Programmatically Part 2

Mattias Described the Scenario in part 1 of this post

Following up on his blog post, I’m going to descrbibe how to script this through SharePoint.

Starting off, we connect to the Site that we believe the User Object is in. Then we create a simple If Else statement that checks if the User Exists, and If so, delete the User.

Here’s the function used in the script.

function RemoveUser([string]$Site, [string]$SiteCollection, [string]$User) {

	# GAC

	[System.Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null
	[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | Out-Null

	# Connect To Sharepoint

	$SPSite = New-Object Microsoft.SharePoint.SPSite($Site)
	$OpenWeb = $SPSite.OpenWeb($SiteCollection)

	# Check if User Exists in Site

	if ($OpenWeb.SiteUsers | Where {$_.LoginName -eq $User}) {
		$User = $OpenWeb.SiteUsers | Where {$_.LoginName -eq $User}

		Write-Host "User: $User Successfully Removed from Site: $Site/$SiteCollection"
	} else {
	Write-Host "User: $User Does not exist on Site: $Site/$SiteCollection"

Here’s a script that automates these steps.


PS > Remove-SPUser.ps1 -Site http://wss -SiteCollection Test -User Domain\User

PS > Remove-SPUser.ps1 -help

Rating 3.50 out of 5

2 thoughts on “Remove Sharepoint Users Programmatically Part 2

  1. Thanks for the script. Its very useful for us. however when i run , i am getting
    The following exception was thrown when trying to enumerate the collection: “0x80070002There is no We
    b named “/site1″.”
    any help will be appreciated .

  2. Pingback: FBA Users automatically being made inactive from a Site Collection | SharePoint Under The Covers

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Anti-Spam Protection by WP-SpamFree