Thursday, January 31, 2013

Replace windows accounts with FBA accounts + SharePoint 2010


Recently I worked on  migration project Moss 2007 to SharePoint 2010.
My requirements like Remove all windows accounts and Replace windows accounts with FBA accounts.

for example

I have 3 windows users in SharePoint site and they are in groups like group1, group2 group3. I hvae to create 3 users into FBA database and replace FBA users with where windows accounts are located.

for this I  have prepared a excel sheet which shows a list of users with below details

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;

here are the steps to follow.

1)     Add FBA users to the SharePoint site. Before writing script you have to consider below scenarios.
a.     Add users to the groups
b.     Add users to the site level who are not belong to the group.
c.     Add users to the SharePoint Lists which has unique permissions.
    2)  Remove windows users    from SharePoint site once FBA users added
    3)  Remove Local Users if they are any.


Please follow below posts






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()

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

UserName,ID
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

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

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


#variables
      $winusername = $null
      $winlogin = $null
      $fbaUserName= $null
      $fbaformattedlogin = $null
      $id= $null
    $groupname = $null
      $i=1
     
      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
           
           
      }
Catch
      {
            # $_ | Out-File d:\surya\errors.txt -Append
          $msg = ( "{0},{1}" -f "Error occurred while removing user:", $_)
            $msg | out-file -FilePath $logfile  -append
      }
     
      $i++
     
           
}
$web.Dispose()
$site.Dispose()


Read users from Sharepoint 2010 site or list unique permissions


Below script reads all windows users from .csv file. It will assign windows user permissions to specific FBA user. Sometimes some of the users will be added to the site level those are not belongs to the group.

This script will work for any sites or lists have unique permissions.


=======.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;


     
function Get-SPUserEffectivePermissions(
    [object[]]$users,
    [Microsoft.SharePoint.SPSecurableObject]$InputObject) {
   
    begin { }
    process {
     
       $i=0
        $so = $InputObject
        if ($so -eq $null) { $so = $_ }
       
        if ($so -isnot [Microsoft.SharePoint.SPSecurableObject]) {
            throw "A valid SPWeb, SPList, or SPListItem must be provided."
        }
           
            $fbauser =$null;
           
        #Write-Host "===================================================================="
            #Write-Host "CAlling function " $weblocal.url  "...."  $fbaformattedlogin
        foreach ($user in $users) {
            # Set the users login name
            $loginName = $user
            if ($user -is [Microsoft.SharePoint.SPUser] -or $user -is [PSCustomObject]) {
                $loginName = $user.LoginName
            }
            if ($loginName -eq $null) {
                throw "The provided user is null or empty. Specify a valid SPUser object or login name."
            }
           
            # Get the users permission details.
            $permInfo = $so.GetUserEffectivePermissionInfo($loginName)
           
                 
            # Determine the URL to the securable object being evaluated
            $resource = $null
            if ($so -is [Microsoft.SharePoint.SPWeb]) {
                $resource = $so.Url
                        #Write-Host  "weburl:"  $so.Url
                                         
            } elseif ($so -is [Microsoft.SharePoint.SPList]) {
                $resource = $so.ParentWeb.Site.MakeFullUrl($so.RootFolder.ServerRelativeUrl)
            } elseif ($so -is [Microsoft.SharePoint.SPListItem]) {
                $resource = $so.ParentList.ParentWeb.Site.MakeFullUrl($so.Url)
            }
                 
                  #if($so.hasuniqueroleassignments -eq "True")
            if (($so.permissions -ne $null) -and ($so.hasuniqueroleassignments -eq "True"))
            {
               #Write-Host "site or list has unique permissions: "  $so.Title
              
              
           
            # Get the role assignments and iterate through them
            $roleAssignments = $permInfo.RoleAssignments
            if ($roleAssignments.Count -gt 0) {
                 
                 
                foreach ($roleAssignment in $roleAssignments) {
                    $member = $roleAssignment.Member
                   
                    # Build a string array of all the permission level names
                    $permName = @()
                    foreach ($definition in $roleAssignment.RoleDefinitionBindings) {
                        $permName += $definition.Name
                    }
                   
                    # Determine how the users permissions were assigned
                    $assignment = "Direct Assignment"
                    if ($member -is [Microsoft.SharePoint.SPGroup]) {
                        $assignment = $member.Name
                    } else {
                        if ($member.IsDomainGroup -and ($member.LoginName -ne $loginName)) {
                            $assignment = $member.LoginName
                        }
                    }
                   
                              if($assignment -eq  "Direct Assignment")
                              {
                                    #Write-Host "=====" $so.Title "  ==========Direct Assignment ===  $resource ==="  $so.GetType().Name "=========================="
                                    #Write-Host "LoginName:" $loginName "===== Permissions: " $permName "===Resource:"  $resource
                                   
                                    $UserName = $fbaformattedlogin  #"i:0#.f|dmidmemberprovider|mhalnon@tech-res.com"
                                    #Write-Host  "Site"  $weblocal  "FBA UserName:" $UserName
                                    Write-Host "UserName" $UserName 
                                   
                                     if ($so -is [Microsoft.SharePoint.SPWeb])
                                     {
                                    $fbauser = $so.SiteUsers[$UserName]
                                 } elseif ($so -is [Microsoft.SharePoint.SPList])
                                     {
                                        $fbauser = $weblocal.SiteUsers[$UserName]
                                 }
                                     
                                    Write-Host $fbauser
                                          #$colRoles = New-Object Microsoft.SharePoint.SPRoleDefinitionCollection
                                         
                                        $colRoles= $weblocal.RoleDefinitions[$permName]
                                         
                                          foreach($spRoleDefinition in $colRoles)
                                          {
                                         
                                           if($spRoleDefinition.Name -ne "Limited Access")
                                                {
                                                 Write-Host "role definitions:"  $spRoleDefinition.Name
                                                   $roledef= $spRoleDefinition.Name
                                                  
                                                      $roleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($fbauser)
                                                      $roleAssignment.RoleDefinitionBindings.Add($spRoleDefinition)
                                                      $so.RoleAssignments.Add($roleAssignment)
                                                     
                                                      $msg = ("{0},{1}" -f "==============================   Permisssions Added: ", " $roledef    $resource =================================")
                                                      $msg | out-file -FilePath $logfile  -append
                                                     
                                                }
                                                elseif($spRoleDefinition.Name -eq "Limited Access")
                                                {
                                                      # $spRoleDefinition=$weblocal.RoleDefinitions["Read"]
                                                      # $roleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($fbauser)
                                                      # $roleAssignment.RoleDefinitionBindings.Add($spRoleDefinition)
                                                      # $so.RoleAssignments.Add($roleAssignment)
                                                }
                                         
                                         
                                          }
                                         
                          #Create a hash table with all the data
                          $hash = @{
                              Resource = $resource
                              "Resource Type" = $so.GetType().Name
                              User = $loginName
                              Permission = $permName -join ", "
                              "Granted By" = $assignment
                          }
                         
                          # Convert the hash to an object and output to the pipeline
                          New-Object PSObject -Property $hash
                                         
                              }
                             
                }
            }
                 
                  } #unique roles
                   $i++
       
                   # if($i -eq 15)
                   # {
                      #Write-Host "count" $i
                        #break;
                    #}
        }
      }

      end {}
}



$URL = "siteurl"
$InputFile="AddUsers-ProjectTracking.csv"

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

$file = ipcsv $InputFile

$i = 1

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

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

$j=1

#variables
      $winusername = $null
      $winlogin = $null
      $fbaUserName= $null
      $fbaformattedlogin = $null
      $action= $null
    $groups = $null
      $groupname = $null
     
foreach ($line in $file)
{
      #get excel sheet cell values 
    $winusername = $line.winUserName
    $action= $line.Action
      $fbaUserName = $line.FBAloweredusername
      $groups =$line.Groups
     
      #formatting fba login with membership
    $fbaformattedlogin = "i:0#.f|dmidmemberprovider|" + $fbaUserName
   
      try
            {
           
            if($i -gt 0)
              {
     
            $gc = Start-SPAssignment
                  $sitelocal = $gc | Get-SPSite $URL
                  $weblocal = $sitelocal.openweb("");
                 
                  Write-Host "======================= $i  User:" $winusername " (Adding Website Level)============================================="
                  $msg = ("{0},{1}" -f "$i User: $winusername", "(Adding Website Level)   =================================")
                  $msg | out-file -FilePath $logfile  -append
                  $sitelocal |  Get-SPWeb | Get-SPUserEffectivePermissions $winusername #| Out-GridView -Title "All Web Permissions for $user"
                 
                 
                  Write-Host "======================= $i   User:" $winusername " (Adding List Level)============================================="
                  $msg = ("{0},{1}" -f "$i User: $winusername", "(Adding List Level)   =================================")
                  $msg | out-file -FilePath $logfile  -append
                  $sitelocal | Get-SPWeb | %{$_.Lists | Get-SPUserEffectivePermissions $winusername} #| Out-GridView -Title "All Web Permissions for $user"
                  $gc | Stop-SPAssignment
                 
                  }
            }
     
      Catch {

                        $msg = ("{0},{1}" -f "Error:", $_)
                        $msg | out-file -FilePath $logfile  -append
              }

      $i++
     
#     if($i -eq 9)
 #  {
#           break;
#     }

}          
     


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


For more information you can follow this post

Followers