Friday, January 30, 2015

Create a SharePoint Group using PowerShell

Here is my script to create new SharePoint group using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell –ErrorAction SilentlyContinue

#Custom Function to Create new SharePoint Group
function Create-SPGroup
{  
    param ($SiteURL, $GroupName, $PermissionLevel, $GroupDescription)  

    try
    {
        #Get the Web
        $web = Get-SPWeb -Identity $SiteURL
        
        if($web -ne $null)
        {
            #Check if Group Exists already
            if ($web.SiteGroups[$GroupName] -ne $null)  
            {  
                write-Host "Group $GroupName exists Already!" -ForegroundColor Red 
            }  
            else  
            {  
                #Create SharePoint Group
                $Web.SiteGroups.Add($GroupName, $web.Site.Owner, $web.Site.Owner, $GroupDescription)  
                #Get the newly created group and assign permission to it
                $Group = $web.SiteGroups[$groupName]  
                $roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($group)  
                $roleDefinition = $web.Site.RootWeb.RoleDefinitions[$permissionLevel]  
                $roleAssignment.RoleDefinitionBindings.Add($roleDefinition)  
                $web.RoleAssignments.Add($roleAssignment)  
                $web.Update()  

                write-Host "Group: $GroupName created successfully!" -ForegroundColor Green
            }  
 
            $web.Dispose() 
        }
    }
    catch [System.Exception]
    {
        write-host $_.Exception.ToString() -ForegroundColor Red 
    }
}

#Call the function to create Sharepoint group
Create-SPGroup "http://sales.crescent.com" "Sales Managers" "Edit" "Group for Sales Managers" 

Tags: create a SharePoint group powershell, create new SharePoint group powershell, create permission group SharePoint 2013 powershell, create SharePoint security group powershell, create SharePoint user group using powershell, powershell to create SharePoint group

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, January 29, 2015

There has been a critical error while processing the form.

Problem: SharePoint browser enabled InfoPath form gave this error message:
There has been a critical error while processing the form. Click Start Over to load a new copy of the form. If this error persists, contact the support team for the Web site.  Click Close to exit this message. 
Error details:
Object doesn't support property or method 'addEventListener'

There has been a critical error while processing the form. Object doesn't support property or method 'addEventListener'

Solution: This is due to Browser compatibility settings. Add your Site under compatibility view settings to resolve this issue.
  • Open your Site in Internet Explorer
  • Go to "Tools" Menu >> Click on "Compatibility View Settings" menu item
  • Add your site to the list!
That's all. Now the browser enabled InfoPath form should render without any issue.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, January 27, 2015

How to Use PowerShell in SharePoint Online

I know I said it several times, but I'll say it again: I'm a big fan of PowerShell! PowerShell makes repetitive tasks easier and less tedious. It helps to automate complex tasks and reduces risk of human error. In this article, I'm exploring how to use PowerShell with SharePoint online.

how to connect to SharePoint online using PowerShell:
Follow these steps to connect to SharePoint online via PowerShell.

Step 1: Download and Install SharePoint online PowerShell module:
You must download and install SharePoint Online Management Shell to start with.  Download PowerShell for SharePoint online at: https://www.microsoft.com/en-us/download/details.aspx?id=35588
install powershell for sharepoint online

Step 2: How to Connect to SharePoint online with PowerShell
Launch "SharePoint Online Management Shell" from start menu and connect to SharePoint Online Administration Center first.
Connect-SPOService -Url https://salaudeen-admin.sharepoint.com `
           -credential salaudeen@salaudeen.onmicrosoft.com
This cmdlet must be run before we use any other SharePoint Online cmdlets. Make sure you connect with an account with the global administrator permissions and use HTTPS in the admin site URL.  You'll get The prompt for password.
Connect to SharePoint online with PowerShell

Step 3: Start using SharePoint online PowerShell cmdlets!
Once connected, you can use SharePoint Online cmdlets. Here are some examples. Lets create a site collection in SharePoint online using PowerShell.

SharePoint online PowerShell create site collection
#Lets create a new Site collection:
New-SPOSite -Url https://salaudeen.sharepoint.com/sites/Sales `
   -Owner salaudeen@salaudeen.onmicrosoft.com -StorageQuota 1000 -Title "Sales Site" 
sharepoint online powershell create site collection

Create group in SharePoint Online with PowerShell ISE:
You can also use PowerShell ISE. Lets create a group using PowerShell for SharePoint online.
#sharepoint online powershell create group:
#Connect to SharePoint Online
Connect-SPOService -Url https://salaudeen-admin.sharepoint.com `
      -credential salaudeen@salaudeen.onmicrosoft.com

#create group
New-SPOSiteGroup -Site https://salaudeen.sharepoint.com/sites/Sales  `
            -Group "Sales Managers" -PermissionLevels "Full Control" 
 sharepoint online powershell create group

Index of SharePoint online PowerShell cmdlets:
For the list of available cmdlets for SharePoint online, Refer: SharePoint online 2013 PowerShell cmdlets at https://technet.microsoft.com/en-us/library/fp161364.aspx
You can also use this cmdlet to list SharePoint online PowerShell cmdlets:
Get-Command –Module Microsoft.Online.SharePoint.PowerShell
list sharepoint online powershell cmdlets

Limitation: Unlike SharePoint on-premises, SharePoint online offers only least set of PowerShell cmdlets to manage SharePoint online. E.g. There is no direct PowerShell cmdlets to activate feature, create subsite, create list, add list item, add user to group, etc. Solution would be utilizing client side object model (CSOM) with PowerShell! I'll write an another post on how to manage SharePoint online with PowerShell and client object model.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Sunday, January 25, 2015

Delete Button Missing in SharePoint Column? Here is How to Delete them.

How to delete a Column when Delete Button is missing:
Unable to delete list column in SharePoint since there is no delete button in field properties? In some cases, columns added through "Add existing columns" doesn't provide the option to delete! To make them deletable, just revert these two properties: AllowDeletion & Sealed
sharepoint column no delete button - sharepoint list sealed and non-deletable columns
Here is how to delete SharePoint list column programmatically with PowerShell: 
#Get the Web
$web = Get-SPWeb "http://sharepoint.crescent.com/sites/pmo"

#Get the List
$list = $web.Lists["Design Documents"]

#Get the column
$column = $list.Fields["Category"]

#Disable Delete
$column.AllowDeletion = $true
$column.Sealed = $false
$column.Update()

#To delete a SharePoint list column in PowerShell, use: $column.Delete() 

$web.Dispose() 
sharepoint column delete button missing
We can also make fields to Sealed, So that nobody can change the field settings.

SharePoint Manager tool  can be used to set these properties. Just navigate to the site, list or library and set the "AllowDeletion" property to false, save the changes. This hides delete option in SharePoint list. sharepoint list column enable disable delete option

Here is my another post to make a column non-deletable: How to Prevent SharePoint List or Columns from Deletion

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, January 21, 2015

Delete a Site Column using PowerShell in SharePoint

To remove a site column in SharePoint, Navigate to:
  • Site Actions >> Site Settings
  • Click on "Site Columns" >> Pick your target site column
  • Scrolldown and click on "Delete" button
sharepoint 2013 powershell delete site column
Delete a Site Column using PowerShell in SharePoint
To delete site column using PowerShell in SharePoint, use this script:
Add-PSSnapin Microsoft.SharePoint.PowerShell –ErrorAction SilentlyContinue

#Variables
$RootWebURL ="http://intranet.crescent.com"

#Internal Name of the site column to delete
$SiteColumnToRemove="Departments"

#Get the Root Web
$RootWeb = Get-SPWeb $RootWebURL

#Check if a site column exists already
    if ($RootWeb.Fields.ContainsField($SiteColumnToRemove))
    {
        #delete site column powershell sharepoint
        $Rootweb.Fields.Delete($SiteColumnToRemove)

        Write-host "Site column has been Deleted Successfully!" 
    }
This removes the site column from SharePoint site!

Tags: delete site column using powershell, delete site column powershell, delete site column powershell , sharepoint delete site column with powershell, delete site column powershell sharepoint 2010, remove site column using powershell, sharepoint remove site column powershell, sharepoint 2010 remove site column powershell

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Create Site Column in SharePoint using PowerShell

The PowerShell way of adding site column is extremely helpful when you have to add site columns in bulk. Say for e.g. You may have certain site columns created in your DEV environment and would like to have them in Staging or in PROD environment. Will you be creating them one by one with SharePoint UI? No! That would be hectic. Here I'm sharing my PowerShell scripts to create site columns in SharePoint.

Add site column to SharePoint with PowerShell
Here is a simple example of creating site column in SharePoint 2013 with PowerShell:
#Get the Root Web
$RootWeb = Get-SPWeb "http://intranet.crescent.com"

#Create a text Field site column
$RootWeb.Fields.Add("ProjectCode","Text",$false)
$SalaryField = $RootWeb.Fields.Add("Crescent-Salary", "Currency", $false)

Create site columns using PowerShell - Lets create in Bulk!
Now, lets add site columns in bulk. Just enter your column names to the array: $SiteColumnsToAdd and run the code.  
Add-PSSnapin Microsoft.SharePoint.PowerShell –ErrorAction SilentlyContinue

#Variables
$RootWebURL ="http://intranet.crescent.com"

#Get the Root Web
$RootWeb = Get-SPWeb $RootWebURL

# List of Site Column Names to be Added
$SiteColumnsToAdd = @("Branch Name", "Branch Code", "Destination")

ForEach($SiteColumn in $SiteColumnsToAdd)
{
    if (!$RootWeb.Fields.ContainsField($SiteColumn))
    {
        #Remove Space in the Field's Internal Name
        $InternalName= $SiteColumn.Replace(" ","")
        #Add new site column
        $RootWeb.Fields.Add($InternalName, "Text", $false)

        #Get the site column
        $Addedcolumn = $RootWeb.Fields.GetField($InternalName)
        #Set the Column Title and Group
        $Addedcolumn.Group="Crescent Columns"
        $Addedcolumn.Title=$SiteColumn
        $Addedcolumn.update()

        Write-host "Site column $($SiteColumn) has been Added Successfully!" 
    }
 } 
$RootWeb.Dispose()

SharePoint 2013 PowerShell to create site column - Choice Field:
Add-PSSnapin Microsoft.SharePoint.PowerShell –ErrorAction SilentlyContinue

#Variables
$RootWebURL ="http://intranet.crescent.com"

#Get the Root Web
$RootWeb = Get-SPWeb $RootWebURL

#Create a Choice Field site column
$RootWeb.Fields.Add("Departments","Choice",$false)

#Get the field by internal Name
$ChoiceField=$RootWeb.Fields.GetField("Departments")

#Set the Site column Group
$ChoiceField.Group="Crescent Columns"

#Add Choices
$ChoiceField.Choices.Add("Operations")
$ChoiceField.Choices.Add("Marketing")
$ChoiceField.Choices.Add("Sales")
$ChoiceField.Choices.Add("Finance")

#Set Title
$ChoiceField.Title="Department Selection"
#Default choice
$ChoiceField.DefaultValue="Sales"
#Allow fill in choices
$ChoiceField.FillInChoice=$true

#Apply changes to the column
$ChoiceField.Update()

Write-host "Site column $($SiteColumn) has been Added Successfully!" 
$RootWeb.Dispose()

SharePoint 2010 create site column using PowerShell - using Field Schema XML Method
The AddFieldAsXml method gives us more flexibility:
Add-PSSnapin Microsoft.SharePoint.PowerShell –ErrorAction SilentlyContinue

#Variables
$RootWebURL ="http://intranet.crescent.com"

#Get the Root Web
$RootWeb = Get-SPWeb $RootWebURL

#Define the Site column XML
$FieldXML = '<Field Type="Number" DisplayName="Bpt-InvoiceNo" Required="TRUE" EnforceUniqueValues="FALSE" Indexed="FALSE" Min="1" Max="10000" Group="Bpt Columns" ID="{b81c7da6-1317-46fa-a32b-9f446c30b6e9}" StaticName="Bpt-InvoiceNo" Name="Bpt-InvoiceNo"></Field>'

#Create site columns with powershell from XML
$RootWeb.Fields.AddFieldAsXml($FieldXML)

Write-host "Site column has been Added Successfully!" 
Refer the Field Element XML to specify field options such as Read Only, Group, Etc.
https://msdn.microsoft.com/en-us/library/office/ms437580.aspx

SharePoint add site column with PowerShell from CSV File
Add-PSSnapin Microsoft.SharePoint.PowerShell –ErrorAction SilentlyContinue

#Variables
$RootWebURL ="http://intranet.crescent.com"
$CSVPath = "D:\SiteColumns.csv"

#Get the Root Web
$RootWeb = Get-SPWeb $RootWebURL

#Import from CSV File
$SiteColumnsCSV = Import-csv -Path $CSVPath #CSV has "Title" column Header

foreach($Column in $SiteColumnsCSV)
{
 #Get the field title from CSV
        $FieldTitle = $Column.Title
     
    #Check if a site column exists already
    if (!$RootWeb.Fields.ContainsField($FieldTitle))
    {
     #Frame FieldXMLString from the column Title
     $FieldXMLString = [String]::Format('<Field Type="Text" Name="{0}" DisplayName="{1}" StaticName="{0}" Required="FALSE"></Field>',$fieldTitle.Replace(" ",""),$FieldTitle)

     #create site column sharepoint 2010 powershell from XML string
     $RootWeb.Fields.AddFieldAsXml($FieldXMLString)

        Write-host "Site column '$($FieldTitle)' has been Added Successfully!" 
    }
}

$RootWeb.Dispose() 

Related Posts: 


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, January 20, 2015

Copy Permissions from One User to Another in SharePoint using PowerShell

Permission management in SharePoint is always a complex task especially on large environments. Granting permissions in SharePoint becomes cumbersome when you are in a situation to clone an existing user's access rights. Consider this scenario: You have an existing user in a department granted access to various SharePoint web applications, sites, lists, files, etc. and when a new user joins to this department, You-SharePoint Administrator get the requirement of adding new user to all of the places with same access rights as the existing team member!

How will you compare access rights of an existing team member and grant access in bulk? He may be granted permission on various levels with different access rights. It would become very time-consuming to find and grant same level of permissions to multiple users on multiple SharePoint objects. Existing user may be grated access as part of:
  • Farm Administrator group and/or as part of web application policies
  • Member of Site collection administrator group
  • Permissions granted at site level either as part of SharePoint group or with direct permissions
  • Permissions granted to list or libraries by breaking inheritance 
  • Access rights may be via List item or folder level permissions.
In short, permissions can be granted at the following levels in SharePoint:
sharepoint copy permissions from one user to another
Well, To copy permissions from one user to another user on above levels, I've written this PowerShell script - It just scans all possible levels for given source user's access rights and grants permission to the target user.

PowerShell script to clone SharePoint User Permissions:
Important: You must run this script as Farm Administrator! Otherwise, you'll get "Access Denied" error!!
This script iterates through each levels as in the above image and copies permissions between given users at List Item/Folder, Lists, site, Site Collection, Web Application and Farm levels. Just change the parameters for variables $SourceUserl, $TargetUser and $WebAppURL accordingly and run the script. You'll find the script outputs logs on the screen, on wherever it copies permissions.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Function to copy user permissions 
Function Copy-UserPermissions($SourceUserID, $TargetUserID, [Microsoft.SharePoint.SPSecurableObject]$Object)
{
 #Determine the given Object type and Get URL of it
    Switch($Object.GetType().FullName)
  {
   "Microsoft.SharePoint.SPWeb"  { $ObjectType = "Site" ; $ObjectURL = $Object.URL; $web = $Object }
 "Microsoft.SharePoint.SPListItem"
   { 
  if($Object.Folder -ne $null)
  {
   $ObjectType = "Folder" ; $ObjectURL = "$($Object.Web.Url)/$($Object.Url)"; $web = $Object.Web
  }
  else
  {
   $ObjectType = "List Item"; $ObjectURL = "$($Object.Web.Url)/$($Object.Url)" ; $web = $Object.Web
  }
   }
   #Microsoft.SharePoint.SPList, Microsoft.SharePoint.SPDocumentLibrary, Microsoft.SharePoint.SPPictureLibrary,etc
   default { $ObjectType = "List/Library"; $ObjectURL = "$($Object.ParentWeb.Url)/$($Object.RootFolder.URL)"; $web = $Object.ParentWeb }
  }
 
 #Get Source and Target Users
 $SourceUser = $Web.EnsureUser($SourceUserID)
 $TargetUser = $Web.EnsureUser($TargetUserID)

 #Get Permissions of the Source user on given object - Such as: Web, List, Folder, ListItem
 $SourcePermissions = $Object.GetUserEffectivePermissionInfo($SourceUser)
 
  #Iterate through each permission and get the details
  foreach($SourceRoleAssignment in $SourcePermissions.RoleAssignments)
  {
    #Get all permission levels assigned to User account directly or via SharePOint Group
    $SourceUserPermissions=@()
        foreach ($SourceRoleDefinition in $SourceRoleAssignment.RoleDefinitionBindings)
        {
      #Exclude "Limited Accesses"
   if($SourceRoleDefinition.Name -ne "Limited Access")
   {
    $SourceUserPermissions += $SourceRoleDefinition.Name
   }
     }
  
  #Check Source Permissions granted directly or through SharePoint Group
    if($SourceUserPermissions)
    {
      if($SourceRoleAssignment.Member -is [Microsoft.SharePoint.SPGroup])
      {
       $SourcePermissionType = "'Member of SharePoint Group - " + $SourceRoleAssignment.Member.Name +"'"
      
       #Add Target User to the Source User's Group
       #Get the Group
       $Group = [Microsoft.SharePoint.SPGroup]$SourceRoleAssignment.Member
       
       #Check if user is already member of the group - If not, Add to group
       if( ($Group.Users | where {$_.UserLogin -eq $TargetUserID}) -eq $null )
       {
         #Add User to Group
         $Group.AddUser($TargetUser)
         #Write-Host Added to Group: $Group.Name
       }
      }
      else
      {
       $SourcePermissionType = "Direct Permission"
      
       #Add Each Direct permission (such as "Full Control", "Contribute") to Target User
       foreach($NewRoleDefinition in $SourceUserPermissions)
       {
        #Role assignment is a linkage between User object and Role Definition
     $NewRoleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($TargetUser)
     $NewRoleAssignment.RoleDefinitionBindings.Add($web.RoleDefinitions[$NewRoleDefinition])

     $object.RoleAssignments.Add($NewRoleAssignment)
     $object.Update()
       }
      }
  $SourceUserPermissions = $SourceUserPermissions -join ";" 
  Write-Host "***$($ObjectType) Permissions Copied: $($SourceUserPermissions) at $($ObjectURL) via $($SourcePermissionType)***"
  }
  }
}
 
Function Clone-SPUser($SourceUserID, $TargetUserID, $WebAppURL)
{
 ###Check Whether the Source Users is a Farm Administrator ###
  Write-host "Scanning Farm Administrators Group..."
 #Get the SharePoint Central Administration site
 $AdminWebApp = Get-SPwebapplication -includecentraladministration | where {$_.IsAdministrationWebApplication}
 $AdminSite = Get-SPWeb $AdminWebApp.Url
 $AdminGroupName = $AdminSite.AssociatedOwnerGroup
 $FarmAdminGroup = $AdminSite.SiteGroups[$AdminGroupName]

 #enumerate in farm adminidtrators groups
    foreach ($user in $FarmAdminGroup.users)
    {
  if($User.LoginName.Endswith($SourceUserID,1)) #1 to Ignore Case
  {
   #Add the target user to Farm Administrator Group
   $FarmAdminGroup.AddUser($TargetUserID,"",$TargetUserID , "")
   Write-Host "***Added to Farm Administrators Group!***"
  }     
    }
 
 ### Check Web Application User Policies ###
  Write-host "Scanning Web Application Policies..."
 $WebApp = Get-SPWebApplication $WebAppURL  
  
 Foreach ($Policy in $WebApp.Policies)
 {
  #Check if the search users is member of the group
      if($Policy.UserName.EndsWith($SourceUserID,1))
  {
   #Write-Host $Policy.UserName
   $PolicyRoles=@()
        foreach($Role in $Policy.PolicyRoleBindings)
        {
         $PolicyRoles+= $Role
        }
  }
 }
 #Add Each Policy found
 if($PolicyRoles)
 {
  $WebAppPolicy = $WebApp.Policies.Add($TargetUserID, $TargetUserID)
  foreach($Policy in $PolicyRoles)
  {
   $WebAppPolicy.PolicyRoleBindings.Add($Policy)
     }
     $WebApp.Update()
    Write-host "***Added to Web application Policies!***"
   }
   
  ### Drill down to Site Collections, Webs, Lists & Libraries, Folders and List items ###
  #Get all Site collections of given web app
  $SiteCollections = Get-SPSite -WebApplication $WebAppURL -Limit All
 
  #Convert UserID Into Claims format - If WebApp is claims based! Domain\User to i:0#.w|Domain\User
    if( (Get-SPWebApplication $WebAppURL).UseClaimsAuthentication)
    {
  $SourceUserID = (New-SPClaimsPrincipal -identity $SourceUserID -identitytype 1).ToEncodedString()
    $TargetUserID = (New-SPClaimsPrincipal -identity $TargetUserID -identitytype 1).ToEncodedString()
    }
  
  #Loop through all site collections 
    foreach($Site in $SiteCollections)
    {
   #Prepare the Target user 
   $TargetUser = $Site.RootWeb.EnsureUser($TargetUserID)
  
      Write-host "Scanning Site Collection Administrators Group for:" $site.Url
    ###Check Whether the User is a Site Collection Administrator
      foreach($SiteCollAdmin in $Site.RootWeb.SiteAdministrators)
        {
   if($SiteCollAdmin.LoginName.EndsWith($SourceUserID,1))
   {
    #Make the user as Site collection Admin
       $TargetUser.IsSiteAdmin = $true
       $TargetUser.Update()
    Write-host "***Added to Site Collection Admin Group***"
   }     
     }

  #Get all webs
  $WebsCollection = $Site.AllWebs
    #Loop throuh each Site (web)
    foreach($Web in $WebsCollection)
    {
   if($Web.HasUniqueRoleAssignments -eq $True)
   {
    Write-host "Scanning Site:" $Web.Url
      
        #Call the function to Copy Permissions to TargetUser
        Copy-UserPermissions $SourceUserID $TargetUserID $Web   
      } 

   #Check Lists with Unique Permissions
   Write-host "Scanning Lists on $($web.url)..."
   foreach($List in $web.Lists)
   {
    if($List.HasUniqueRoleAssignments -eq $True -and ($List.Hidden -eq $false))
    {
     #Call the function to Copy Permissions to TargetUser
     Copy-UserPermissions $SourceUserID $TargetUserID $List
    }
     
    #Check Folders with Unique Permissions
        $UniqueFolders = $List.Folders | where { $_.HasUniqueRoleAssignments -eq $True }
                #Get Folder permissions
    if($UniqueFolders)
    {
                 foreach($folder in $UniqueFolders)
           {
           #Call the function to Copy Permissions to TargetUser
                     Copy-UserPermissions $SourceUserID $TargetUserID $folder     
     }
    }
     
        #Check List Items with Unique Permissions
       $UniqueItems = $List.Items | where { $_.HasUniqueRoleAssignments -eq $True }
    if($UniqueItems)
    {
                 #Get Item level permissions
                 foreach($item in $UniqueItems)
           {
           #Call the function to Copy Permissions to TargetUser
           Copy-UserPermissions $SourceUserID $TargetUserID $Item 
     }
    }
      }
    }
  }
 Write-Host "Permission are copied successfully!"  
}
#Define variables for processing
$WebAppURL = "http://sharepoint.crescent.com"

#Provide input for source and Target user Ids
$SourceUser ="Crescent\TonyW"
$TargetUser ="Crescent\Salaudeen"

#Call the function to clone user access rights
Clone-SPUser $SourceUser $TargetUser $WebAppURL 

Copy User Permissions at list level:
This script is broken into two functions: Copy-UserPermissions and Clone-SPSuer for convenience. Lets say, you want to copy permissions at list level, then you can utilize the Copy-UserPermission function as:
 
$WebURL = "http://sharepoint.crescent.com/sites/sales"

$web = Get-SPWeb $WebURL

$SourceUser ="i:0#.w|Crescent\TonyW"
$TargetUser ="i:0#.w|Crescent\Salaudeen"

$list = $Web.Lists["Invoice"]

#$folder = $list.Folders[0]
#$ListItem = $list.Items[0]

#Call the function to copy user permissions programmatically at LIST level
Copy-UserPermissions $SourceUser $TargetUser $list

This script just clone's user permissions at list level (copies at only list level, no drill-down to Folders and Items!).

Please note, This script doesn't clone permissions which are granted via Active Directory Security groups!


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


SharePoint 2013: PowerShell to Create a Folder in Document Library

How to add folder in SharePoint Document Library using PowerShell:
To create folder in document library in SharePoint 2013, use this PowerShell script:
$folder = $list.Folders.Add("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, "New")
$folder.Update()
The above codes doesn't provide much fault tolerance, isn't it?
  • What if the particular library we are looking for doesn't exists?
  • What if the folder we are trying to add already exists on the library?
Error! So lets re-write the code in PowerShell with little fault tolerance!
create folder in sharepoint document library powershell

How to Create Folders and Sub-Folders in SharePoint List using PowerShell?

Here is the PowerShell code snippet for creating Folders and Sub-Folders inside SharePoint List or Library:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Get the Web
$web=Get-SPWeb "http://sharepoint.company.com"
#Get the List/Library
$list=$web.Lists.TryGetList("SalesList")

if($list)  #Check If List exists!
 {
  # Create a Folder "Sales Documents"
  # Check Folder Doesn't exists in the Library!
  $folder = $list.ParentWeb.GetFolder($list.RootFolder.Url + "/" +"Sales List");
  #sharepoint powershell check if folder exists
  if ($folder.Exists -eq $false)
   {
    #Create a Folder
    $folder = $list.AddItem("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, "Sales Sub-Item")
    $folder.Update();
   }
   
  #Create a Sub-Folder "APAC Sales Documents" inside "Sales Documents"
  #Check if sub-folder doesn't exists already
  $Subfolder = $list.ParentWeb.GetFolder($folder.URL + "/" + "APAC Sales Documents");
  if ($Subfolder.Exists -eq $false)
   {
    #Create a Sub-Folder Inside "Sales Documents"
    $Subfolder = $list.AddItem($folder.URL, [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, "APAC Sales Documents")
    $Subfolder.Update();
   }
 }

Tags: sharepoint powershell folders add, sharepoint 2013 powershell add folder to document library, sharepoint 2013 powershell add folder, sharepoint powershell create folder,  sharepoint powershell create subfolder, sharepoint powershell create folder in document library, sharepoint create folder in list powershell, sharepoint powershell new folder

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, January 19, 2015

The text entered for Person or Group Column isn’t an item from the list. Select an item from the list, or enter text that matches one of the listed items

Problem: End-user wants to copy paste bunch of rows from Excel to SharePoint using Datasheet view. Datasheet view doesn't allow user to paste the data for Person or Group type column! it gives the error message:
The Text entered for the "Person or Group column" isn’t an item from the list. Select an item from the list, or enter text that matches one of the listed items.
The text entered for Person or Group Column isn’t an item from the list. Select an item from the list, or enter text that matches one of the listed items

Root cause: This is by design! SharePoint 2010 datasheet view uses Microsoft access run time engine, which doesn't has any interface to connect and resolve user names from active directory (or any other authentication provider). So, it fetches user names from User information list of SharePoint site collection. That being said: If you enter a new user who is not there in UIL, datasheet view can't resolve it!

Workaround:
In order to fix this problem, prior copy-pasting to datasheet view, we should have them all in user information list! So, Just add all users from people picker column values to SharePoint site (E.g. you can add them to any group like site visitors) that will add users to UIL automatically!

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Friday, January 16, 2015

Disable Throttling on SharePoint List using PowerShell

Throttling feature helps to avoid performance hits in SharePoint. We set throttling limits for entire web application. Its not possible to set throttling limits on specific SharePoint list or library. But we can disable/enable throttling on SharePoint lists.

PowerShell to disable list throttling:
Use the below script to disable list throttling in SharePoint 2010 using PowerShell
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Variables for Site URL and List Name
$WebURL = "http://sales.crescent.com"
$ListName = "Proposal Documents"
 
#Get the Site and List objects
$web = Get-SPWeb $WebURL
$List = $Web.Lists[$ListName]

#Disable throttling on the list
$list.EnableThrottling = $false
$List.Update() 

Related post: Configure Resource Throttling in SharePoint 2013 using PowerShell

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, January 15, 2015

Run PowerShell Script as Administrator (Elevated Privileges) by Default

Its a common SharePoint Administrator's pitfall - Forget to run PowerShell script using "Run as Administrator" option, failing so could lead to many *weird* issues while running PowerShell scripts in SharePoint, such as: "The local farm is not accessible. Cmdlets with FeatureDependencyId are not registered.".
Solution:
Solution is pretty simple! just right click the SharePoint 2013 PowerShell Snap-in and choose the option "Run as Administrator".
 run as administrator powershell script

Enable "Run as Administrator" elevated privilege for SharePoint 2013 Management Shell by default:
To run PowerShell script as administrator automatically, Create a shortcut to your PowerShell console on your desktop
  • Right-click the "SharePoint 2013 Management Shell" shortcut and click Properties
  • Click "Advanced" button under Shortcut tab
  • Enable "Run as Administrator" and click on "OK" button.
powershell script always run as administrator
Now you can run PowerShell in elevated mode by simply double-clicking the new shortcut on your desktop.

Run PowerShell as administrator in scheduled tasks:
If you are scheduling a PowerShell script, make sure you select the "Run With Highest Privileges" check box. Otherwise your scheduled task which invokes a UAC prompt may fail to run unattended.

Handle Run as Administrator with in PowerShell script:
Lets handle it in our PowerShell code itself, even you forget to use "Run as Administrator" option!
Function Check-RunAsAdministrator()
{
  #Get current user context
  $CurrentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
 
  #Check user is running the script is member of Administrator Group
  if($CurrentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator))
  {
       Write-host "Script is running with Administrator privileges!"
  }
  else
    {
       #Create a new Elevated process to Start PowerShell
       $ElevatedProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";

       # Specify the current script path and name as a parameter
       $ElevatedProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"

       #Set the Process to elevated
       $ElevatedProcess.Verb = "runas"

       #Start the new elevated process
       [System.Diagnostics.Process]::Start($ElevatedProcess)

       #Exit from the current, unelevated, process
       Exit

    }
}

#Check Script is running with Elevated Privileges
Check-RunAsAdministrator

#Place your script here.
write-host "Welcome"
add this code at the beginning of your script.

Run as a Different User in PowerShell scripts:
$credential = New-Object System.Management.Automation.PsCredential("Domain\UserID", (ConvertTo-SecureString "Password" -AsPlainText -Force))
Start-Process powershell -Credential $credential -NoNewWindow
 
How to run PowerShell as administrator from the command line? 
To run PowerShell as administrator in command line:
  1. Type : PowerShell to enter into PowerShell console
  2. Now, Type: Start-Process PowerShell -Verb RunAs
BTW, There could be some more reasons for "The local farm is not accessible. Cmdlets with FeatureDependencyId are not registered" issue such as:
Another solution to address this issue: Disable UAC! Here is how - How to Disable UAC in Windows Server 2012/2008


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, January 12, 2015

Create New Custom List in SharePoint using PowerShell

Requirement: Add custom list to SharePoint using PowerShell.

PowerShell Script to Create New List:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Function to create custom list
Function Create-List($SiteURL, $ListName)
{
    #Set the Error Action
    $ErrorActionPreference = "Stop"

    Try {
        $Web = Get-SPWeb -Identity $SiteURL
        $ListTemplate = [Microsoft.SharePoint.SPListTemplateType]::GenericList
       
        #Check if List with specific name exists
        if($Web.Lists.TryGetList($ListName) -eq $null)
        {
            $List = $Web.Lists.Add($ListName, $ListName, $ListTemplate)  
            write-host "List Created Successfully!" -ForegroundColor Green
        }
        else
        {
            write-host "List with specific name already exists!" -ForegroundColor Red
        }
    }
    catch {
        Write-Host $_.Exception.Message -ForegroundColor Red
    }
    finally {
        #Reset the Error Action to Default
        $ErrorActionPreference = "Continue"
    }
}

#Parameters to create new List
$SiteURL="http://intranet.crescent.com/"
$ListName = "Customer Directory"

#Call the funtion to create new custom list
Create-List $SiteURL $ListName

This PowerShell script creates new custom list in SharePoint with "Title" column. If you want to add more columns to the list using PowerShell, Refer: How to Add Fields to SharePoint List using PowerShell.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, January 10, 2015

SharePoint 2013 Patch (Service Pack-CU-Hotfix) Installation Guide - Step by Step

So you want to maintain your SharePoint environment healthy, secure, stable and up to date by installing latest patches? Well, this article walks through the various steps involved in installing patches for your SharePoint 2013 environment.

SharePoint 2013 patching best practices
Before proceeding , Lets consider some of the best practices for SharePoint 2013 patching. I would strongly recommend patching your development/test SharePoint farms first before proceeding with the production environment. Make sure Dev/Test environments are thoroughly tested, all custom/third-party components are fully functional. Watch those environments, Identify and address common issues and then schedule the maintenance window for your SharePoint 2013 production farm.

Always, Its a good idea to stay one CU behind the current release (or 3 to 6 Moths behind latest patch) for production environments to avoid any potential issues that may be introduced by a new CU. Simply installing the latest updates is not a best practice and may put your environment at risk. Take snapshot backups of your SharePoint servers before applying updates. (That's why I'm a big fan of SharePoint server visualization!). This will help when things don’t go right.

Downtime Mitigation: If you have a TEST environment (or call it QA/Pre-Production) closer to production, you can backup-restore SharePoint content databases, make them read-only, change the publishing servers to point TEST farm as Production farm during this maintenance window. Keep your user community aware of this maintenance window. Plan and send out a proper e-mail communication about the scheduled maintenance. SharePoint 2013 provides an excellent way SharePoint 2013 Maintenance Window Notifications

It is no longer required to install the SharePoint Foundation patches before proceeding with SharePoint Server patches.

SharePoint 2013 patch procedure
At high level, SharePoint 2013 patching process is done as follows:
  1. Get your current farm patch level
  2. Download SharePoint 2013 service pack/CU/Hot-fix
  3. Install binaries on SharePoint Servers
  4. Run the SharePoint Products Configuration Wizard
  5. Verify the updated build number of your SharePoint farm.

Step 1: Get SharePoint 2013 Patch Level

There are many ways to find SharePoint build numbers including PowerShell (more info:  How to find SharePoint Farm Build Version Number/Patch Level ). Here is the easiest way to find SharePoint patch level:
  • Go to your SharePoint 20103 Central Administration site. 
  • From the Central Administration, navigate to System Settings >> Manage Servers in this Farm
  • From the Servers in this Farm page, under the Farm information section, you will see the SharePoint Farm Build Version.
sharepoint 2013 check sharepoint patch level
To match the build number with SharePoint 2013 patch, use Todd Klindt's blog: http://www.toddklindt.com/blog/Lists/Posts/Post.aspx?ID=346

Step 2: SharePoint 2013 patch download
To start with SharePoint 2013 patching, We must download the relevant patches first!. The major difference in downloading patches for SharePoint 2013 and its previous versions is: You don't have to download and install patches for both SharePoint Foundation and SharePoint Server, if you are running with SharePoint 2013 server. You can just download and install SharePoint Server patch alone!!

To download SharePoint 2013 service packs, hot-fixes and cumulative updates(CU), head on to Microsoft SharePoint updates site: http://technet.microsoft.com/library/dn789211(v=office.14)
You have to download the relevant patch depending on your SharePoint environment version/edition and patch level.
Download all patches to a network location so that you do not have to download for every server in the farm!

Step 3: Install SharePoint patch Binaries
The next step is to install service pack/patches to all SharePoint servers (except the database server). You can start with SharePoint App Server(s) that host Central Administration first.
  • Browse to the location where you downloaded patches. 
  • Start the patching process by double clicking the installers (you may have to extract the downloaded binaries!). Accept the license agreement and click on "Continue".
sharepoint 2013 service pack installation
  •  You should see the installation progress window. You may asked to reboot the server to complete patch installation.
  •  Wait for the installation is complete message.

Install Patches on All other servers in the Farm:
You must install any patch on every server in your SharePoint farm including WFE and App servers. SharePoint 2013 Products Configuration Wizard is good enough to detect and prevent you from proceeding, If you try to run SharePoint 2013 Products Configuration Wizard without installing binaries on all servers.
sharepoint 2013 patch management
Install all other required binaries before proceeding with the next step.

Step 4: Run SharePoint 2013 Products Configuration Wizard
Once binaries are installed on all SharePoint servers, The next step is run SharePoint 2010 Products Configuration Wizard.
  • Go to start >> Search "SharePoint products configuration wizard" and run PSConfig wizard as administrator. Click on Next to continue.
sharepoint 2013 foundation patch
  • You will get a warning message saying few services will be restarted during this upgrade process. Click Yes and then Click Next
  •  SharePoint products configuration wizard will run through the upgrade process. Wait for the wizard to complete.
  •  When the wizard is completed, click Finish.
sharepoint 2013 patching best practices
Repeat this patch procedures in rest your SharePoint Servers in the farm.

Run SharePoint 2013 Products Configuration Wizard ONE Server at a time:
We have to run SharePoint 2013 products configuration wizard in all other servers. Although SharePoint patch installation can happen simultaneously, I would suggest you run SharePoint Products Configuration Wizard only on ONE sever at a time! Start from App Server which hosts central admin, Once its completed move on to other app servers and then SharePoint web front ends. SharePoint 2013 patching process may take about 30 minutes on each server.

If you try to run the wizard simultaneously, You'll get to see SharePoint 2013 places a lock until the configuration gets completed on the other server already running the wizard.

Step 5: Verify Installation for SharePoint 2013 Service Pack:
We have successfully installed patches in our SharePoint 2013 environment. To verify patching and make sure installation is successful lets check the farm's build number. There are many ways to find SharePoint build number (more info:  How to find SharePoint Farm Build Version Number/Patch Level ). Here is the easiest one:
  • Go to your SharePoint 20103 Central Administration site. 
  • From the Central Administration, navigate to System Settings >> Manage Servers in this Farm
  • From the Servers in this Farm page, under the Farm information section, you will see the Configuration Database Version.
sharepoint 2013 service pack version number
Make sure your new build number is matching with the patch your have just installed. Also, check "Manage Servers in this Farm" page in Central administration. This page will also tell you if you need to run the SharePoint Products Configuration Wizard on a server to complete the update process. Make sure every server in your SharePoint farm is upgraded and displays status as "No Action Required".
SharePoint 2013 patch status page:
You can check the patch status on each and every individual server with "Manage patch status page" (Central Administration >> Upgrade and Migration >> Check product and patch installation status.
sharepoint 2013 patch status page
"Check upgrade status" page gives insights on detailed upgrade status information.
sharepoint 2013 patch status page
Don't just stop by SharePoint 2013 service pack installation. But apply Windows Server OS patches and SQL Server patches on regular maintenance windows. Make sure All SharePoint Services are stopped before starting your patching process.

SharePoint 2013 Service installation failed?
In case of failure, review the error log presented to determine the source . Simply re-running the products configuration wizard worked for me any times! or you may have to run psconfig command instead of running the wizard.
psconfig -cmd upgrade -inplace b2b -wait
or try:
PSConfig.exe -cmd upgrade -inplace b2b -force -cmd applicationcontent -install -cmd installfeatures
 
What is the difference between service pack, Cumulative updates and hot fixes (or patches)?
  • Hotfix/patch is a update addressing a specific problem/bug/security issue. On Demand - normally not for everyone, you should only apply the patch if you're having the specific problem it addresses. Microsoft publishes a corresponding KB article for every hotfix that is released for every Microsoft product. 
  • Cumulative Updates  - As their name suggest, they are cumulative in content so they include a collection previously released hotfixes to date. Hotfixes and CUs are not always publicly released.  You'll get a link to download these hotfixes and CUs on requesting via Microsoft site. 
  • Service pack is a collection of CUs (and patches). It rolls together all patches that have come along over a given period of time. - Usually contains new features and available to public.
Every Hotfix, CU, Service pack you install, will increment the version/build number of your SharePoint Farm.

Last but not least: Its a good idea to have a maintenance page during scheduled down times in SharePoint: Maintenance Page for SharePoint - Quick way to Implement  

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, January 5, 2015

Sync SharePoint List Data from a CSV File using PowerShell

Requirement: We've a SharePoint list with number of fields to capture organization wide people Expertise. This list has a particular field called "Team" and is to be updated from a CSV file of 100+ rows. Yes, Datasheet view can help, but the problem is: The Team field value to be updated on items matching "AccountName" field of the SharePoint list and CSV file.
Sync SharePoint List Data from a CSV File using PowerShell
Solution:
Lets write a PowerShell script to select the matching row from the CSV file to SharePoint list and then update it.

PowerShell Script to sync SharePoint List data from CSV File:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Read the CSV file
$CSVData = Import-CSV -path "C:\Expertdata.csv" 
 
#Get the Web
$web = Get-SPWeb -identity "http://portal.crescent.com"
 
#Get the Target List
$list = $web.Lists["ExpertProfiles"]
$TeamsLookupList =  $web.Lists["Teams"]

#Iterate through each Row in the CSV
foreach ($row in $CSVData) 
 {
   #Get the matching Row from Experts List in SharePoint
   $item = $list.Items | Where-Object {$_["AccountName"] -eq $row.AccountName}
   
     if($item -ne $null)
     {
         Write-Host "Found Matching User in the Experts List:"$row.AccountName
    
         #If the CSV data has valid Team data
         if( ( $row.Team -ne $null) -and ( $row.Team -ne "") )
         {
             #Get Team Field Value (Lookup column) from the Expert Item
             $ExpertTeam = New-Object Microsoft.SharePoint.SPFieldLookupValue($Item["Team"])

             #If the current Team Value is empty or Null 
             if ( ($ExpertTeam.LookupValue -eq $null) -or ( $ExpertTeam.LookupValue -eq ""))
             {
                #Get the Team from Parent Lookup List
                $LookupItem = $TeamsLookupList.Items | where {$_["Team"] -eq $row.Team} | Select-Object -First 1
    
                $item["Team"] = $LookupItem.ID
                $item.Update()
                Write-Host "Updated Team in:"$row.AccountName -ForegroundColor Green
             }
         }
    }
 }
 
I've added additional validations such as: Checking if the current Team field value is empty as per the business requirements.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


SharePoint 2013 User Permission Analysis & Reporting using PowerShell

Analysing SharePoint permissions for a particular user is often a common task in SharePoint administration. Generally, How do we check what permissions a user has on SharePoint content? By getting into site or list settings page and check permissions for the particular user, isn't it? Well, You may want to analyze the particular user's permissions for your entire SharePoint environment.  How about that? Each and every SharePoint site, list, library, folder and list items may have unique permissions. It can even go more challenging when you have multiple SharePoint farms.

Well, PowerShell is the life saver! Here is my permission reporting solution to scan and provide a report to view a user's permission on the SharePoint web application. With this script, you can analyze and track the security effectively! Check what permissions on an account has been granted in all places in SharePoint. This PowerShell script scans below areas to retrieve a specific user's access rights:
  • Farm administrator's group
  • Central administration web application policies
  • Site collection administrators 
  • Scans all site collections and sub-sites with unique permissions in which user has access.
  • Scans all lists and libraries with unique permissions in which user has access.
  • Scans all folders and list Items which has permissions in the site in which user has access.
Just change the Input variables section and provide parameters for User Id, Web Application and Report path variables and run the script in PowerShell.

After generating a SharePoint permissions report, this script generates a CSV file, which can be export as excel file to allows the further research and analyze outside of a SharePoint environment. It gets data such as:  Object, Title, URL, Permission Type, Permissions as in the below screenshot.
PowerShell Script to Generate User Permission Report in SharePoint 2010/2013

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Function to retrieve Permission data
Function Get-PermissionInfo([String]$UserID, [Microsoft.SharePoint.SPSecurableObject]$Object)
{
 #Object Array to hold Permission data
    $PermissionDataCollection = @()

 #Determine the given Object type and Get URL of it
    switch($Object.GetType().FullName)
 {
  "Microsoft.SharePoint.SPWeb"  { $ObjectType = "Site" ; $ObjectURL = $Object.URL }
  "Microsoft.SharePoint.SPListItem" 
  { 
   if($Object.Folder -ne $null)
   {
     $ObjectType = "Folder" ; $ObjectURL = "$($Object.Web.Url)/$($Object.Url)" 
   }
   else
   {
    $ObjectType = "List Item"; $ObjectURL = "$($Object.Web.Url)/$($Object.Url)" 
   }
  }
  #Microsoft.SharePoint.SPList, Microsoft.SharePoint.SPDocumentLibrary, "Microsoft.SharePoint.SPPictureLibrary",etc
  default { $ObjectType = "List/Library"; $ObjectURL = "$($Object.ParentWeb.Url)/$($Object.RootFolder.URL)" }
 }
 
 #Get Permissions of the user on given object - Such as: Web, List, Folder, ListItem
 $UserPermissionInfo = $Object.GetUserEffectivePermissionInfo($UserID)
 #Iterate through each permission and get the details
 foreach($UserRoleAssignment in $UserPermissionInfo.RoleAssignments)
 {
  #Get all permission levels assigned to User account directly or via SharePOint Group
  $UserPermissions=@()
        foreach ($UserRoleDefinition in $UserRoleAssignment.RoleDefinitionBindings)
        {
   #Exclude "Limited Accesses"
   if($UserRoleDefinition.Name -ne "Limited Access")
   {
          $UserPermissions += $UserRoleDefinition.Name
   }
        }
 
  #Determine Permissions granted directly or through SharePoint Group
  if($UserPermissions)
  {
   if($UserRoleAssignment.Member -is [Microsoft.SharePoint.SPGroup])   
   {
     $PermissionType = "Member of SharePoint Group: " + $UserRoleAssignment.Member.Name     
   }
   else
   {
    $PermissionType = "Direct Permission"
   }
   $UserPermissions = $UserPermissions -join ";"  
 
   #Create an object to hold storage data
         $PermissionData = New-Object PSObject
         $PermissionData | Add-Member -type NoteProperty -name "Object" -value $ObjectType
   $PermissionData | Add-Member -type NoteProperty -name "Title" -value $Object.Title
         $PermissionData | Add-Member -type NoteProperty -name "URL" -value $ObjectURL  
   $PermissionData | Add-Member -type NoteProperty -name "Permission Type" -value $PermissionType
   $PermissionData | Add-Member -type NoteProperty -name "Permissions" -value $UserPermissions
   $PermissionDataCollection += $PermissionData
  }   
 } 
 Return $PermissionDataCollection
}

#Function to Generate Permission Report
Function Generate-PermissionReport($UserID, $WebAppURL, $ReportPath)
{
    #Output Report location, delete the file, If already exist!
    if (Test-Path $ReportPath)
     {
        Remove-Item $ReportPath
     }
  
   #Write Output Report CSV File Headers
  "Object, Title, URL, Permission Type, Permissions" | out-file $ReportPath

 ###Check Whether the Search Users is a Farm Administrator ###
 Write-host "Scanning Farm Administrators..." 
   #Get the SharePoint Central Administration site
   $AdminWebApp = Get-SPwebapplication -includecentraladministration | where {$_.IsAdministrationWebApplication}
    $AdminSite = Get-SPWeb $AdminWebApp.Url
    $AdminGroupName = $AdminSite.AssociatedOwnerGroup
    $FarmAdminGroup = $AdminSite.SiteGroups[$AdminGroupName]
 
 #enumerate in farm adminidtrators groups
    foreach ($user in $FarmAdminGroup.users)
    {
     if($user.LoginName.Endswith($UserID,1)) #1 to Ignore Case
     {
       "Farm, $($AdminSite.Title), $($AdminWebApp.URL), Farm Administrators Group, Farm Administrator" | Out-File $ReportPath -Append
     }     
    }
 
 ### Check Web Application User Policies ###
 Write-host "Scanning Web Application Policies..." 
  $WebApp = Get-SPWebApplication $WebAppURL
 
  foreach ($Policy in $WebApp.Policies)
  {
      #Check if the search users is member of the group
     if($Policy.UserName.EndsWith($UserID,1))
       {
       #Write-Host $Policy.UserName
        $PolicyRoles=@()
       foreach($Role in $Policy.PolicyRoleBindings)
       {
        $PolicyRoles+= $Role.Name +";"
       }
   #Send Data to CSV File
      "Web Application, $($WebApp.Name), $($WebApp.URL), Web Application Policy, $($PolicyRoles)" | Out-File $ReportPath -Append
   }
  }

 #Convert UserID Into Claims format - If WebApp is claims based! Domain\User to i:0#.w|Domain\User
    if($WebApp.UseClaimsAuthentication)
    {
        $ClaimsUserID = (New-SPClaimsPrincipal -identity $UserID -identitytype 1).ToEncodedString()
    }
 
 #Get all Site collections of given web app
 $SiteCollections = Get-SPSite -WebApplication $WebAppURL -Limit All

 #Loop through all site collections 
    foreach($Site in $SiteCollections)
    {
     Write-host "Scanning Site Collection:" $site.Url
  ###Check Whether the User is a Site Collection Administrator
     foreach($SiteCollAdmin in $Site.RootWeb.SiteAdministrators)
        {
      if($SiteCollAdmin.LoginName.EndsWith($ClaimsUserID,1))
      {
       "Site Collection, $($Site.RootWeb.Title), $($Site.RootWeb.Url), Site Collection Administrators Group, Site Collection Administrator" | Out-File $ReportPath -Append
      }     
    }
  
  #Get all webs
  $WebsCollection = $Site.AllWebs
  #Loop throuh each Site (web)
  foreach($Web in $WebsCollection)
  {
       if($Web.HasUniqueRoleAssignments -eq $True)
             {
     Write-host "Scanning Site:" $Web.Url
    
     #Get Permissions of the user on Web
     $WebPermissions = Get-PermissionInfo $ClaimsUserID $Web
     
     #Export Web permission data to CSV file - Append
     $WebPermissions |  Export-csv $ReportPath  -notypeinformation -Append 
    } 
    
    #Check Lists with Unique Permissions
    Write-host "Scanning Lists on $($web.url)..."
    foreach($List in $web.Lists)
    {
              if($List.HasUniqueRoleAssignments -eq $True -and ($List.Hidden -eq $false))
                 {
      #Get Permissions of the user on list
                        $ListPermissions = Get-PermissionInfo $ClaimsUserID $List
      
      #Export Web permission data to CSV file - Append
      $ListPermissions |  Export-csv $ReportPath -notypeinformation -Append       
     }
    
     #Check Folders with Unique Permissions
     $UniqueFolders = $List.Folders | where { $_.HasUniqueRoleAssignments -eq $True }                    
                    #Get Folder permissions
                    foreach($folder in $UniqueFolders)
        {
                        $FolderPermissions = Get-PermissionInfo $ClaimsUserID $folder
    
      #Export Folder permission data to CSV file - Append
      $FolderPermissions |  Export-csv $ReportPath -notypeinformation -Append    
                    }
    
     #Check List Items with Unique Permissions
     $UniqueItems = $List.Items | where { $_.HasUniqueRoleAssignments -eq $True }
                    #Get Item level permissions
                    foreach($item in $UniqueItems)
        {
                        $ItemPermissions = Get-PermissionInfo $ClaimsUserID $Item
      
      #Export List Items permission data to CSV file - Append
      $ItemPermissions |  Export-csv $ReportPath -notypeinformation -Append    
                    }
    }
  }
 }
 Write-Host Permission Report Generated successfully!
}

#Input Variables
$WebAppURL = "http://intranet.crescent.com"
$Userid ="Crescent\Salaudeen" 
$ReportPath = "D:\Reports\PermissionRpt.csv"

#Call the function to generate user access report
Generate-PermissionReport $Userid $WebAppURL $ReportPath
You can also download the script from Technet gallery: SharePoint Permission Report: Check Access Rights for a Specific User

This script is broken into two functions. So that you can use the first function: Get-PermissionInfo to get permissions data scoped to a site collection permission report/site. Above script scoped at a particular web application. You can call the same function on all your web application to get the entire SharePoint permissions reports.

PowerShell Scripts to generate SharePoint Permission Reports:
Here is my list of PowerShell scripts to create various reports for SharePoint permission auditing.

3rd Party Tools:
There are many tools in the market to analyze, audit SharePoint user permissions (and more features naturally!). Here are some:


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, January 3, 2015

SharePoint Online: Activate Feature using PowerShell

Requirement: Activate a feature in SharePoint online site collection using PowerShell.

Solution: In SharePoint On-Premises, We use: Enable-SPFeature cmdlet to activate/enable features. In SharePoint online there is no such cmdlet available through PowerShell to activate feature. But we can utilize Client Side Object Model (CSOM) to activate feature in SharePoint online. Lets activate "SharePoint Server Publishing Infrastructure" feature
Make sure you have SharePoint Server 2013 Client Components SDK installed in your machine to use Client side assemblies. You can download it from: http://www.microsoft.com/en-us/download/details.aspx?id=35585

SharePoint online: PowerShell script to enable feature
#Load SharePoint CSOM Assemblies
Import-Module Microsoft.Online.SharePoint.Powershell

#Variables for Processing
$SiteURL = "https://crescent.sharepoint.com/Sites/Sales"
$FeatureGUID =[System.GUID]("f6924d36-2fa8-4f0b-b16d-06b7250180fa") #Publishing Feature ID
$LoginName ="Salaudeen@crescent.OnMicrosoft.com"
$LoginPassword ="Password" 

#Get the Client Context
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)

#Login Credentials
$SecurePWD = ConvertTo-SecureString $LoginPassword –asplaintext –force  
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $LoginName, $SecurePWD
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Credential.UserName,$Credential.Password)

#Get the Site
$site = $ctx.site

#sharepoint online powershell activate feature
$site.Features.Add($FeatureGUID, $force, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::farm)    

$ctx.ExecuteQuery()  
write-host "Feature has been Activated!" 

SharePoint Online: PowerShell to Activate Feature
Lets Add some error handling to the above code and create a reusable function
#Load SharePoint Online CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Function to Enable Feature in SharePoint Online
Function Enable-SPOFeature 
{ 
    param ($SiteCollURL,$UserName,$Password,$FeatureGuid)
    Try 
    {     
        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteCollURL)
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $Password)
        $Ctx.Credentials = $Credentials
        $Site=$Ctx.Site

        #Check the Feature Status
        $FeatureStatus =  $Site.Features.GetById($FeatureGuid)
        $FeatureStatus.Retrieve("DefinitionId")
        $Ctx.Load($FeatureStatus)
        $Ctx.ExecuteQuery()

        #Activate the feature if its not enabled already
        if($FeatureStatus.DefinitionId -eq $null)
        {
            Write-Host "Enabling Feature $FeatureGuid..." -ForegroundColor Yellow
            $Site.Features.Add($FeatureGuid, $true, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::None) | Out-Null
            $Ctx.ExecuteQuery()
            Write-Host "Feature Enabled on site $SiteCollURL!" -ForegroundColor Green
        }
        else
        {
            Write-host "Feature is Already Active on the Site collection!" -ForegroundColor Red
        }
    } 
    Catch
    {
        write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
    }
}
 
#Parameters to Activate Feature
$SiteCollURL = "https://Crescent.sharepoint.com/sites/Demo"
$UserName = "SPAdmin@Crescent.com"
$Password = "Password goes here"
$FeatureGuid= [System.Guid] ("f6924d36-2fa8-4f0b-b16d-06b7250180fa") #Publishing Feature
$SecurePassword= ConvertTo-SecureString $Password –asplaintext –force  

#Enable Feature
Enable-SPOFeature -SiteCollURL $SiteCollURL -UserName $UserName -Password $SecurePassword -FeatureGuid $FeatureGuid


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Friday, January 2, 2015

How to Hide Column Headers in SharePoint List View Web Parts using CSS, jQuery

I was looking for some ways to hide SharePoint list view column headers today. Here are my findings:
  1. You can use CSS to hide column headers
  2. Use JavaScript/JQuery to Hide column headers
  3. You can edit the page in SharePoint designer and remove column headers

Hide Column Headers of All List View using CSS in SharePoint 2010-2013-2016:
Insert a CEWP just below your list view web part and place this code in it.
<style type="text/css">

  tr.ms-viewheadertr
  {
     display: none
  }

</style>
This will hide all list view web part headers.
Hide Column Headers in List View Web Parts
The headers of your web part should now be hidden. The above code hides headers of every web part in the page. Its helpful when the page contains a web part using with boxed style list views.

You can also hide specific web part's header using this CSS:
 #WebPartWPQxxxx .ms-viewheadertr
  {
     display: none
  }

Where xxxx is the web part ID. Use IE Toolbar/Firebug to find it.

jQuery to find and Hide specific Web Part Headers:
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script> 
<script language="javascript" type="text/javascript">
 
$(document).ready(function(){
$("table[summary='LIST NAME'] tr:eq(0)").hide();
});
 
</script>
Don't forget to change the LIST NAME in the above code!


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


You might also like:

Related Posts Plugin for WordPress, Blogger...