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}
		$OpenWeb.SiteUsers.Remove($User)

		Write-Host "User: $User Successfully Removed from Site: $Site/$SiteCollection"
	} else {
	Write-Host "User: $User Does not exist on Site: $Site/$SiteCollection"
	}
	$SPSite.Dispose()
	$OpenWeb.Dispose()
}

Here’s a script that automates these steps.

Usage:


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

PS > Remove-SPUser.ps1 -help


Rating 3.50 out of 5
[?]
Categories: Sharepoint Tags:
  1. Manjiri
    September 28th, 2011 at 18:32 | #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 .

  1. No trackbacks yet.

Comment Spam Protection by WP-SpamFree