Friday, August 15, 2014

Remove list of Users from all site collections in farm using powershell script

Remove list of Users from all site collections in farm using powershell script

Copy below code and save it as removeusers.ps1 

=========================================================
param
(
[Parameter(Mandatory=$true)][ValidateScript({Test-Path $_ -Include "*.csv"})]
[String]$CSVPath
)
#This script will remove users specified in the CSV.
$CSVFile = Import-CSV $CSVPath
Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
#Get all site collections
$Sites = Get-SPSite -Limit All
$AllSites = @()
foreach($Line in $CSVFile)
{
foreach($Site in $Sites)
{
#Get the rootweb for the site collection
        $RootWeb = $Site.RootWeb
If([bool](Get-SPUser $Line.Username -Web $RootWeb -EA SilentlyContinue) -eq $True)
{
#Remove the user from the User Information List
        Remove-SPUser -Identity $Line.username -Web $RootWeb -Confirm:$False
$AllSites += $RootWeb.Url
}
}
if(!($AllSites).count -eq 0)
{
#Give feedback on deleted users
Write-Host “Removed user $($Line.username) from:” -Fore “Magenta”
foreach($S in $AllSites){Write-Host “- $S”}
Write-Host “”
$AllSites = @()
}
}

================================================

Open notepad and add below list of users and save it as .csv extension file

=============
username
domain\user1
domain\user2
================

Run the script with below command:
C:>.\removeusers.ps1 users.csv



No comments:

Post a Comment