Thursday, January 31, 2013

Remove SharePoint 2010 local users using PowerShell

Below script removes local users from SharePoint site. This one expects parameter Id you can see user id in the url when you click on any user account in the SharePoint site. Here I have prepared list of users in the csv file and looping through the users.
Sample .CSV file

Test1user  ,256
Test2user ,243
Test3user  ,239

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

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

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

      $winusername = $null
      $winlogin = $null
      $fbaUserName= $null
      $fbaformattedlogin = $null
      $id= $null
    $groupname = $null
      Write-Host "Started"
foreach ($line in $file)

#get excel sheet cell values 
    $winusername = $line.UserName
    $id= $line.ID
      Write-Host "Winuser:" $winusername $line.ID
try  {
            $msg = ("{0},{1}" -f "$i  User:  $winusername", "")
            $msg | out-file -FilePath $logfile  -append
            $list=$web.Lists["User Information List"]
            $listItem = $list.GetItemById($id)

            write-Host("User Removed " + $listItem["Account"])
            remove-spuser $listItem["ID"] -web $web  -confirm:$false
            $msg = ("{0},{1}" -f "$winusername - Removed from site successfully", "")
            $msg | out-file -FilePath $logfile  -append
            # $_ | Out-File d:\surya\errors.txt -Append
          $msg = ( "{0},{1}" -f "Error occurred while removing user:", $_)
            $msg | out-file -FilePath $logfile  -append

No comments:

Post a Comment