Monday, July 18, 2016

Read Excel particular column values and ensure the user in SharePoint site using powershell

Declare Parameters:

Param(
  [string]$filePath,
  [string]$sheetName,
  [string]$siteUrl,
  [string]$authFormat,
  [string]$authProviderName
)

#$filePath = "C:\venkat\MDM.xlsx"
#$sheetName = "Sheet1"

$objExcel = New-Object -ComObject Excel.Application
$workbook = $objExcel.Workbooks.Open($filePath)
$sheet = $workbook.Worksheets.Item($sheetName)
$objExcel.Visible=$false

$rowMax = ($sheet.UsedRange.Rows).count

Write-Host ("last row is: "+$lastRow)
# mention column name to read from the Excel (here 2nd column is read)
$rowUserID,$colUserID = 1,2

for ($i=1; $i -le $rowMax-1; $i++)
{
  $UserID = $sheet.Cells.Item($rowUserID+$i,$colUserID).text
  if ($UserID)
   {    
     $loginName="";  
     #$authProviderName ="";
     #$authFormat = "i:0#.w";
   
     if(!$authProviderName)
      {
         # authProviderName is empty value
         $loginName =   $authFormat+"|"+$UserID;        
       }
     else
     {
       $loginName =   $authFormat+"|"+$authProviderName+"|"+$UserID;
     }

     Write-Host ("UserID is: "+$loginName)

     $spsite = new-object Microsoft.SharePoint.SPSite($siteUrl);

     $web = $spsite.openweb()    

     $claim = New-SPClaimsPrincipal -Identity $UserID -IdentityType WindowsSamAccountName

     $user=$web.EnsureUser($claim.ToEncodedString());
   
     #$user=$web.EnsureUser($UserID);

     Write-Host ("valid user is: "+$user)  
   }
}

$objExcel.quit()