Thursday, January 31, 2013

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

No comments:

Post a Comment

Followers