Thursday, January 31, 2013

Remove users from SharePoint 2010 Site with Powershell


When you run this script it will ask you to provide .csv file location. It reads one by one user from csv file and removes the user from SharePoint site.


=======.csv file sample data====================


winUserName,       Email,   FBAloweredusername, Groups

domain1\surya1 , surya1@xxx.com ,surya1, group1, group2, group3, group4;

domain1\surya2, surya2@xxx.com ,surya2, group1;group4;

domain1\surya3, surya3@xxx.com ,surya3, group1; group2; group3; group4;




param([string]$URL = "siteurl", [string]$InputFile=$(Read-Host -prompt "Path to CSV File containing users and groups:"))

#add-pssnapin Microsoft.SharePoint.Powershell

$site = New-Object Microsoft.SharePoint.SPSite($URL)
$web = $site.openweb("")

$file = ipcsv $InputFile

$i = 1
$j=1

#logging
$timestamp = get-date -format "yyyyMMdd_hhmmtt"
$filenameStart = "MigrationLogRemoveUsers"
$logfile = ("{0}{1}.csv" -f $filenamestart, $timestamp)

$header = "Message,Error"
$header | out-file -FilePath $logfile


      #variables
      $winusername = $null
      $winlogin = $null
      $fbaUserName= $null
      #$fbaformattedlogin = $null
      $action= $null
    $groupname = $null
     

     
foreach ($line in $file)
{

      #get excel sheet cell values 
    $winusername = $line.winUserName
    $action= $line.Action

      $msg = ("{0},{1}" -f "$i  UserName: $winusername", "")
      $msg | out-file -FilePath $logfile  -append
            Write-Host "============== $i  UserName:  $winusername  ================="
     
      #loop through the group names
            try
                  {
                              $web.SiteUsers.Remove($winusername)
                              Write-Host "$winusername - Removed from site successfully"
                              $msg = ("{0},{1}" -f "$winusername - Removed from site successfully", "")
                              $msg | out-file -FilePath $logfile  -append
                             
                  }
            Catch
                  {
                        # $_ | Out-File d:\surya\errors.txt -Append
                      $msg = ( "{0},{1}" -f "Error occurred while removing user:", $_)
                        $msg | out-file -FilePath $logfile  -append
                  }
                       
      #}
     
     
      $i++
       
#     if($i -eq 3)
 #  {
#           break;
#     }

}          
           
$web.Dispose()
$site.Dispose()

No comments:

Post a Comment

Followers