Friday, 2 November 2012

Remove user From all Groups

PowerShell script to remove a user from all groups in a web app


param($web_app_url=$(read-host "Please provide web app url of the list to be delete (EG:'http://Wingtip'):"))

function LoadSharePointPowerShellEnviroment
{
write-host "Setting up Powershell enviroment for Sharepoint" -foregroundcolor Blue
Add-PSSnapin "Microsoft.Sharepoint.PowerShell" -ErrorAction SilentlyContinue
Write-host "Sharepoint PowerShell Snapin loaded." -foregroundcolor Green
}

try
{
    if($web_app_url -eq $null -or $web_app_url -eq '')
    {
        throw "You must specify your server name. Value provided was null/empty."
    }
   
    $UserToRemove = $(read-host "Please Provide the User to remove; include the domain eg: domain/smithj")
   
    if($UserToRemove -eq $null -or $UserToRemove -eq '')
    {
        throw "You must specify your user to remove. Value provided was null/empty."
    }
   
    LoadSharePointPowerShellEnviroment
   
    $site = new-object Microsoft.SharePoint.SPSite($web_app_url)
    $web = $site.OpenWeb()
   
    $web.SiteUsers.Remove($UserToRemove)
}
catch [Exception]
{
    Write-Host -ForegroundColor Red "Error: $_"
}  
finally
{
    $web.Dispose()
    $site.Dispose()
}