Home > Sharepoint > Remove Sharepoint Users Programmatically Part 2

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.00 out of 5
[?]
Categories: Sharepoint Tags:
  1. No comments yet.
  1. No trackbacks yet.

Spam Protection by WP-SpamFree