Tuesday, 21 June 2016

Create Office 365 Group using Powershell

Office 365 Groups provide a platform for collaboration that enables teams to come together and establish a single team identity and a single set of permissions across different Office 365 apps including Outlook, OneDrive, OneNote, Skype for Business, Power BI and Dynamics CRM. In this article, I am going write powershell commands to create Office 365 Groups, add members and owners to an Office 365 Group.

Before proceed, first connect Exchange Online Powershell session by using the following commands.
$365Logon = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $365Logon -Authentication Basic -AllowRedirection
Import-PSSession $Session
We can use the PowerShell cmdlet New-UnifiedGroup to create a new Office 365 group. This cmdlet includes the following key parameters:

DisplayName – display name of the new group
Alias – Email alias of the group. If you omit the parameter, it will generate an alias by using display name.
AccessType – Privacy type of the group (Public or Private)
AutoSubscribeNewMembers – Add this parameter to auto subscribe new members to the group

Use the below command to create a new group with minimal parameters.
New-UnifiedGroup –DisplayName "Test O365 Group 1"
Create the group with key parameters.
New-UnifiedGroup –DisplayName "Test O365 Group 2" -Alias "TestO365Group2" -AccessType Public
Once we created the group, we can use Get-UnifiedGroup cmdlet to list all the available groups.

Add Members and Owners to Office 365 Group

We can use Add-UnifiedGroupLinks cmdlet to add members and owners to the group. This cmdlet includes the following key parameters:

Identity – Alias, Display name, or Email address of the group
Links – Alias, Display name, or Email address of the user being added
LinkType – Members, Owners, or Subscribers

Add an user as owner: To add an user as owner to the group, first we need the user as a member to the specified group.
Add-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Members –Links Morgan
Add-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Owners –Links Morgan
Add member:
Add-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Members  –Links AlexD
Add subscriber: A subscriber who receives updates by email can be added by changing the LinkType to "Subscribers"
Add-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Subscribers  –Links AlexD
The parameter Links accept multiple values, use the following syntax: value1,value2.... If the values contain spaces or otherwise require quotation marks, use the following syntax: "value1","value2",....

Add members to multiple office 365 groups:

$Groups = "group 01","group 02","group 03"
$Groups | ForEach-Object {
Add-UnifiedGroupLinks –Identity $_ –LinkType Members  –Links "Morgan" }

Import office 365 group members from a CSV File:

You can use the below powershell commands to add members to an office 365 group by importing users from csv file. Consider the csv file members.csv that includes the column member which holds the member identity in each row of the csv file.
Import-CSV "C:\members.csv" | ForEach-Object {
Add-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Members  –Links $_.member
}

Find members and owners of a group:

Once we added the members and owners, we can use Get-UnifiedGroupLinks cmdlet to get members or owners of a specific group. The below command lists all members of the given group.
Get-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Members
List owners of a group.
Get-UnifiedGroupLinks –Identity "TestO365Group2" –LinkType Owners
Read More...

Friday, 17 June 2016

Set Storage Quota for Office 365 Group Site using PowerShell

As you know, Office 365 Group is nothing but a hidden site collection that are not visible in Site Collections view in Office 365 Admin portal. You can only access these site collections by using PowerShell or through URL (https://<tanentname>.sharepoint.com/sites/<group-name>/Shared documents”). Since you can't view the site in Office 365 Admin portal, the only way set storage size limit is using Powershell. In this article, I am going to write powershel script to set maximum storage size and storage warning level for Office 365 group site.

We can use the SharePoint Online Powershell cmdlet Set-SPOSite to set storage quota and storage warning size limit. Before proceed, run the following command to connect Sharepoint Online powershell module.
Connect-SPOService -Url https://<tanentname>-admin.sharepoint.com -Credential admin@o365domain.com
Now, run the following script to set storage quota and warning level.
$StorageQuota= 2048 # 2GB or 2048MB
$WarningLevel = 1800 # 1800MB

$siteUrl ="https://<tanentname>.sharepoint.com/sites/<group-name>"
Set-SPOSite -Identity $siteUrl -StorageQuota $StorageQuota -StorageQuotaWarningLevel $WarningLevel

Set Storage Quota for all Office 365 Groups Site:

To set the storage quota for all the Office 365 Groups, first, we need to get sharepoint site url for all the office 365 groups by using Exchange Online cmdlet Get-UnifiedGroup. The following powershell script update storage quota and warning level for all the office 365 groups. You need to replace your own Office 365 tenant name and admin credentials.
$userName ="admin@<tanentname>.onmicrosoft.com" 
$o365Cred = Get-Credential -UserName $userName -Message "Enter Office 365 Admin Credentials"
$o365Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $o365Cred -Authentication Basic -AllowRedirection
Import-PSSession $o365Session

$spoAdminUrl ="https://<tanentname>-admin.sharepoint.com/" 
Connect-SPOService -Url $spoAdminUrl -Credential $o365Cred 

$O365Groups = Get-UnifiedGroup -ResultSize Unlimited

$StorageQuota= 2048 # 2GB or 2048MB
$WarningLevel = 1800 # 1800MB

ForEach ($O365Group in $O365Groups){ 
If($O365Group.SharePointSiteUrl -ne $null) {
$siteUrl = $O365Group.SharePointSiteUrl
Set-SPOSite -Identity $siteUrl -StorageQuota $StorageQuota -StorageQuotaWarningLevel $WarningLevel 
}
}
Once you set the storage quota, you can use the Powershell cmdlet Get-SPOSite to get current storage quota and warning level. The following script list storage quota of all the office 365 groups site.

$O365Groups = Get-UnifiedGroup -ResultSize Unlimited
$CustomResult=@() 
ForEach ($O365Group in $O365Groups){ 
If($O365Group.SharePointSiteUrl -ne $null) 
{ 
   $O365GroupSite=Get-SPOSite -Identity $O365Group.SharePointSiteUrl 
   $CustomResult += [PSCustomObject] @{ 
     GroupName =  $O365Group.DisplayName
     SiteUrl = $O365GroupSite.Url 
     StorageQuota_inGB = $O365GroupSite.StorageQuota/1024
     WarningSize_inGB =  $O365GroupSite.StorageQuotaWarningLevel/1024
     CurrentStorage_inMB = $O365GroupSite.StorageUsageCurrent
  }
}} 
 
$CustomResult | FT
Read More...

Thursday, 16 June 2016

Get the storage used by Office 365 groups using Powershell

Office 365 Groups are nothing but a hidden site collection with mailbox that are not visible in Site Collections view in Office 365 tenant Admin portal. You can only access these site collections by using PowerShell or through URL (https://<tanentname>.sharepoint.com/sites/<group-name>/Shared documents”). Often, Office 365 administrators need to find the storage used by Office 365 groups since this storage gets the storage quota of the SharePoint Site Collections. In this post, I am going to write powershel script to find storage used by office 365 groups.

We can use the SharePoint Online Powershell cmdlet Get-SPOSite to get current site storage size and storage quota. Before proceed, run the following command to connect Sharepoint Online powershell module.
Connect-SPOService -Url https://<tanentname>-admin.sharepoint.com -Credential admin@o365domain.com
Now run the below script after replacing the <tanentname> and <group-name> with your own tenant name and group name.
$O365GroupSiteUrl ="https://<tanentname>.sharepoint.com/sites/<group-name>"
$O365GroupSite = Get-SPOSite -Identity $O365GroupSiteUrl
$StorageSize =$O365GroupSite.StorageUsageCurrent 
                
Write-Host "Storage  used (MB): " $StorageSize " MB" -ForegroundColor Yellow
Write-Host "Storage  used (GB): " ($StorageSize/1024) " GB" -ForegroundColor Yellow

Get the current Storage Size for all Office 365 Groups:

To get the storage used by all Office 365 Groups, first, we need to get sharepoint site url for all the office 365 groups by using Exchange Online cmdlet Get-UnifiedGroup. The following powershell script gets current storage size and storage quota of all the office 365 groups. You need to replace your own Office 365 tenant name and admin credentials.
$userName ="admin@<tanentname>.onmicrosoft.com" 
$o365Cred = Get-Credential -UserName $userName -Message "Enter Office 365 Admin Credentials"

$o365Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $o365Cred -Authentication Basic -AllowRedirection
Import-PSSession $o365Session

$spoAdminUrl ="https://<tanentname>-admin.sharepoint.com/" 
Connect-SPOService -Url $spoAdminUrl -Credential $o365Cred 

$O365Groups = Get-UnifiedGroup -ResultSize Unlimited

$CustomResult=@() 

ForEach ($O365Group in $O365Groups){ 
If($O365Group.SharePointSiteUrl -ne $null) 
{ 
   $O365GroupSite=Get-SPOSite -Identity $O365Group.SharePointSiteUrl 
   $CustomResult += [PSCustomObject] @{ 
     GroupName =  $O365Group.DisplayName
     SiteUrl = $O365GroupSite.Url 
     StorageUsed_inMB = $O365GroupSite.StorageUsageCurrent
     StorageQuota_inGB = $O365GroupSite.StorageQuota/1024
     WarningSize_inGB =  $O365GroupSite.StorageQuotaWarningLevel/1024
  }
}} 
 
$CustomResult | FT
You can also export the output into csv file:
$CustomResult | Export-CSV "C:\\O365-Group-Storage-Info.csv" -NoTypeInformation -Encoding UTF8
Read More...

Thursday, 9 June 2016

Convert Int64 TimeStamp to DateTime in Powershell

Some Applications (Ex: Active Directory ) stores DateTime value as TimeStamp value in a way to support different time zone. The Int64 TimeStamp is nothing but Windows file time. The Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC).

In Powershell, we can use the .Net function FromFileTime and convert the output to DateTime format.
$timestamp = "131099683087123361"
[DateTime]::FromFileTimeutc($timestamp)
You can also convert the standard datetime to timestamp value by using the function ToFileTimeUtc.
$date = Get-Date
$date.ToFileTimeUtc()
In Active Directory environment, the attributes LastLogonTimeStamp and PwdLastSet are stored as Int64 TimeStamp. When you query these properties by using Get-ADUser cmdlet, you need to explicitly convert LastLogonTimeStamp value into datetime value.
Get-ADUser -Identity 'Smith' -Properties LastLogonTimeStamp | 
Select-Object -Property "Name", @{n="LastLogon";e={[datetime]::FromFileTime($_."LastLogonTimeStamp")}}
The following powershell command convert AD user's PwdLastSet value to datetime value.
Get-ADUser -Identity 'Smith' -Properties PwdLastSet | 
Select-Object -Property "Name", @{n="PwdLastSet";e={[datetime]::FromFileTime($_."PwdLastSet")}}
Read More...

Wednesday, 8 June 2016

List Office 365 Group Members using Powershell

The post helps you to list office 365 group (not distribution group) members by using powershell script. We can list all the office 365 groups by using the powershell cmdlet Get-UnifiedGroup and its group members by Get-UnifiedGroupLinks cmdlet.

Note: Before proceed, Connect Exchange Online Remote PowerShell.

The following command lists all the office 365 groups.
Get-UnifiedGroup | Select DisplayName,GroupType,PrimarySmtpAddress

List Office 365 Group Members

We can use the powershell cmdlet Get-UnifiedGroupLinks to view the members of an existing group. The key parameters for this cmdlet are:

Identity – the alias of the group
LinkType – Members, Owners, or Subscribers. Required.

Use the below powershell command to select members of a single office 365 group.
Get-UnifiedGroupLinks -Identity '<group-name>' -LinkType Members
If you want to list members of all the office 365 groups, first, we need to get the results of Get-UnifiedGroup, then we can pipe the output to ForEach-Object and get members for all the office 365 groups.
$Groups = Get-UnifiedGroup -ResultSize Unlimited
$Groups | ForEach-Object {
$group = $_
Get-UnifiedGroupLinks -Identity $group.Name -LinkType Members | ForEach-Object {
      New-Object -TypeName PSObject -Property @{
       Group = $group.DisplayName
       Member = $_.Name
       EmailAddress = $_.PrimarySMTPAddress
       RecipientType= $_.RecipientType
}}}

Export All Office 365 Group Members to CSV

We can export powershell output into CSV file using Export-CSV cmdlet. The following command exports all the office 365 group members to CSV file.
$Groups = Get-UnifiedGroup -ResultSize Unlimited
$Groups | ForEach-Object {
$group = $_
Get-UnifiedGroupLinks -Identity $group.Name -LinkType Members | ForEach-Object {
      New-Object -TypeName PSObject -Property @{
       Group = $group.DisplayName
       Member = $_.Name
       EmailAddress = $_.PrimarySMTPAddress
       RecipientType= $_.RecipientType
}}} |

Export-CSV "C:\\Office365GroupMembers.csv" -NoTypeInformation -Encoding UTF8
Read More...

Tuesday, 7 June 2016

List all Parameters for a Cmdlet in Powershell

When you start work with a new Powershell cmdlet, you might want to get a list of all the available parameters in the powershell cmdlet. We can use the command GET-Command to display all the parameters.
 (GET-Command GET-Process).parameters
We can also use the command Get-Help to display all the available parameters with details.
Get-Help GET-Process -Parameter *
If you want to view only required or mandatory parameters in a cmdlet, we can filter the results using Where-Object with Required property.:
Get-Help GET-Process -Parameter * | Where-Object {$_.Required -eq $true}
Read More...

Tuesday, 31 May 2016

Find AD Users who never logged on using Powershell

We can use the Active Directory powershell cmdlet Get-ADUser to query users from AD. We can find and get a list of AD users who never logged in at least one time by checking the AD attribute value lastlogontimestamp.

The below command lists all users who never logged on.
Get-ADUser -Filter {(lastlogontimestamp -notlike "*")} | Select Name,DistinguishedName
If you want to list only enabled ad users, you can add one more check in the above filter.
Get-ADUser -Filter {(lastlogontimestamp -notlike "*") -and (enabled -eq $true)} | Select Name,DistinguishedName
If you are familiar with LDAP filter you can also find never logged in users by using ldap filter.
Get-ADUser -ldapfilter '(&(!lastlogontimestamp=*)(!useraccountcontrol:1.2.840.113556.1.4.803:=2))' |
 Select Name,DistinguishedName
In most cases, we may want to find AD users who created in last certain days or months and not logged in their system. To achieve this, we need to filter users by created time.

The below powershell command lists all AD users who are created in 30 days before and still not logged in.
$days = 30
$createdtime = (Get-Date).Adddays(-($days))
Get-ADUser -Filter {(lastlogontimestamp -notlike "*") -and (enabled -eq $true) -and (whencreated -lt $createdtime)} | 
Select Name,DistinguishedName

Export Never Logged On AD Users to CSV file:

We can export users into CSV file using Export-CSV cmdlet. The following command export all the never logged in users who are created in 30 days before into CSV file.
$createdtime = (Get-Date).Adddays(-(30))
Get-ADUser -Filter {(lastlogontimestamp -notlike "*") -and (enabled -eq $true) -and (whencreated -lt $createdtime)} | 
Select Name,DistinguishedName |
Export-CSV "C:\\NeverLoggedOnUsers.csv" -NoTypeInformation -Encoding UTF8
Read More...

Monday, 30 May 2016

Create Distribution Group in Office 365 using Powershell

In this article, I am going write powershell commands to create Distribution Groups and add members to a Distribution Group in Office 365 environment. We can use the Exchange Online powershell cmdlet New-DistributionGroup to create a new distribution list.

Before proceed, first connect Exchange Online Powershell session by using the following commands.
$365Logon = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $365Logon -Authentication Basic -AllowRedirection
Import-PSSession $Session
After connecting Exchange Online service, run the following command to create a Distribution Group.

Syntax:
New-DistributionGroup -Name <DG name> -DisplayName <DG display name> -Alias <Alias>
Example
New-DistributionGroup -Name "DG-Sales" -DisplayName "DG-Sales" -Alias "DG-Sales"

Add members to Distribution List:

We can use the cmdlet Add-DistributionGroupMember to add member to distribution group in office 365.
Add-DistributionGroupMember "DG-Sales" -Member Morgan

Add members to multiple Distribution groups:

$Groups = "DG 01","DG 02","DG 03"
$Groups | ForEach-Object {
Add-DistributionGroupMember -Identity $_ –Member "Morgan" }

Import Distribution Group members from a CSV File:

You can use the below powershell commands to add members to Distribution List by importing members from csv file. Consider the csv file members.csv that includes the column member which holder the member identity in each row of the csv file.
Import-CSV "C:\members.csv" | ForEach-Object {
Add-DistributionGroupMember -Identity "DG-Sales" -Member $_.member
}
Read More...

Sunday, 15 May 2016

Get sharepoint lists with more than 5000 items using csom

In this article, I am going to write C# code to retrieve sharepoint lists with more than 5000 items using Clinet Object Model (csom). The magic limit 5000 is a default list view threshold in sharepoint online. To find total lists items in a list, we don't need to iterate all items from list, instead we can get it from the property ItemCount in sharepoint client object model's List object.

Get all Lists with ItemCount:

Use the below C# code to get all sharepoint lists with their total item count.
public static void GetAllListsWithItemCount()
{
    string sitrUrl = "https://Tenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        Web site = ctx.Web;
        ctx.Credentials = //Use your credentials
        ctx.Load(site, a => a.Lists.Include(l => l.Title, l => l.ItemCount));
        ctx.ExecuteQuery();

        foreach (var list in site.Lists)
        {
            Console.WriteLine(list.Title+" : "+ list.ItemCount);
        }
    }
}

Get Lists with more than 5000 items:

The above code returns all the lists with itemcount. To get the lists with more than 5000 items, we need to filter lists with the ItemCount property in linq query.
public static void GetListsWithMoreThan5000Items()
{
    string sitrUrl = "https://Tenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        Web site = ctx.Web;
        ctx.Credentials = //Use your credentials
        ctx.Load(site, a => a.Lists.Where(l => l.ItemCount > 5000),
            a => a.Lists.Include(l => l.Title, l => l.ItemCount));
        ctx.ExecuteQuery();

        foreach (var list in site.Lists)
        {
            Console.WriteLine(list.Title + " : " + list.ItemCount);
        }
    }
}

Get Document Libraries with more than 5000 items:

You can also get only document libraries by filtering List object with BaseType property.
public static void GetLibrariesWithMoreThan5000Items()
{
    string sitrUrl = "https://Tenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        Web site = ctx.Web;
        ctx.Credentials = //Use your credentials
        ctx.Load(site, a => a.Lists.Where(l => l.BaseType == BaseType.DocumentLibrary &&
                 l.ItemCount > 10 && !l.Hidden),
        a=>a.Lists.Include(l => l.Title, l => l.ItemCount));
        ctx.ExecuteQuery();

        foreach (var library in site.Lists)
        {
            Console.WriteLine(library.Title + " : " + library.ItemCount);
        }
    }
}
Read More...

Tuesday, 3 May 2016

How to grant permission for specific attributes in AD

As an Active Directory admin sometimes we may require to allow and deny permission for only specific attributes on AD user object or container (OU) object. In this post, I am going to write steps to assign or remove permissions on Active Directory attributes.

Note: To perform this action, you must be a member of the Domain Admins group, or the Enterprise Admins group in AD, or you must have been delegated the appropriate authority.

Follow the below steps to set permission for individual AD attributes:

  • Open Active Directory Users and Computers console (Start -> Control Panel -> Administrative Tools -> Active Directory Users and Computers). 
  • Click on the View menu, select Advanced Features.
  • Right-click the object (user or ou) for which you want to assign or remove permissions, and then click Properties.
  • On the Security tab, click Advanced to view all the available permissions.
  • Click the button Add, find user or group account whom you want provide access, and click OK.
  • In the "Permission for object name" dialog, go to the "Properties" tab, and select the required properties and desired permissions from the list and save the changes.
Read More...

Thursday, 28 April 2016

Update AD User Home Directory by using PowerShell

Sometimes Active Directory Administrator requires to change user's 'Home Folder' profile mapping location from old file server to new file server. We can use the AD powershell cmdlet Set-ADUser to update user detail. It has a parameter -HomeDirectory , which allows you to set the user's home directory and it also has a parameter -HomeDrive that update the drive letter for their home directory.

Before proceed run the following command to import Active Directory module.
Import-Module ActiveDirectory
The below powershell command set the home directory path and link home drive for the user 'Smith'
Set-ADUser -Identity "Smith" -HomeDirectory "\\fileServer\Users\Smith" -HomeDrive H
You can also find an user and set their DisplayName or samAccountName as home directory folder.
# Get the user, based on their "samAccountName"
$user = Get-ADUser -LDAPFilter '(samAccountName=Smith)';
# Change the user's samAccountName as home directory
$homeDirectory = '\\fileserver\users\' + $user.SamAccountName;
Set-ADUser -Identity $user.SamAccountName -HomeDirectory $homeDirectory -HomeDrive H

Set Home Directory for all AD users from OU:

When we change user's home folder while migrating file server, we need to update for bulk of AD users. If you placed group of users under certain OU, you can get all users from that OU by setting target OU scope in Get-ADUser cmdlet and change home directory path for every user.
$users = Get-ADUser -Filter * -SearchBase "OU=TestOU,DC=TestDomain,DC=com" 
$users | ForEach-Object {
# Assign user's home directory path
$homeDirectory = '\\fileserver\users\' + $_.SamAccountName;
Set-ADUser -Identity $_.SamAccountName -HomeDirectory $homeDirectory -HomeDrive H;
}

Update Bulk AD Users Home Directory from CSV:

We can also set bulk AD users home directory path by importing user details from CSV file. First consider the csv file Users.csv which includes user's display name or samaccountname, the following powershell script import AD user's display name from csv file and set home directory path by using their samAccountName.
# Import user details from CSV
$users = Import-Csv -Path "C:\Users.csv"

# Iterate every row to set each user ...
foreach ($user in $users) {
    # Get the user, based on their "displayName". If you have samAccountName in you csv file,
    # you can replace displayName by samAccountName
    $userAccount = Get-ADUser -LDAPFilter ('(displayname={0})' -f $user.DisplayName);
    # Assign user's home directory path
    $homeDirectory = '\\fileserver\users\' + $userAccount.SamAccountName;
    # Finally set their home directory and home drive letter in Active Directory
    Set-ADUser -Identity $userAccount.SamAccountName -HomeDirectory $homeDirectory -HomeDrive H
}
Read More...

Add or Remove Item Level Permission in SharePoint using CSOM

In this article I am going to write C# code sample to Add or Remove Item Level Permissions using CSOM (Client Object Model). Sometimes we might have a business requirement to give read permission for some users on certain document item and give write permission to other users on the same list item. To achieve this need, we need to add explicit permission for the particular list item. To add unique permission, first we need to stop inheriting permissions (break the inheritance) of the particular document item.

Set Item Level Permission in SharePoint Online:

The following CSOM based c# code first removes the inheritance of a list item and grant unique permission.
public static void AddItemLevelPermissions()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        var web = ctx.Web;
        ctx.Load(ctx.Web, a => a.Lists);
        ctx.ExecuteQuery();

        List list = ctx.Web.Lists.GetByTitle("TestDocLibrary");
        string itemName = "TestFile.txt";
        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml = "" +itemName +
            "";
        var listItems = list.GetItems(camlQuery);
        ctx.Load(listItems, a => a.Include(i => i.HasUniqueRoleAssignments));
        ctx.ExecuteQuery();

        foreach (var listItem in listItems)
        {
            if (!listItem.HasUniqueRoleAssignments)
            {
                listItem.BreakRoleInheritance(false, false);
                ctx.ExecuteQuery();
            }
            var roleAssignments = listItem.RoleAssignments;            
            //var user_group = web.SiteGroups.GetByName("Site Members");
            var user_group = web.SiteUsers.GetByLoginName("i:0#.f|membership|admin@sptenant.onmicrosoft.com");
            var roleDefCol = new RoleDefinitionBindingCollection(ctx);
            // Add Role Definition i.e Full Controls, Contribute or Read rights etc..
            roleDefCol.Add(web.RoleDefinitions.GetByType(RoleType.Contributor));
            roleAssignments.Add(user_group, roleDefCol);
            ctx.Load(roleAssignments);
            listItem.Update();                    
            ctx.ExecuteQuery();
        }
    }
}

Remove/Delete Item Level Permission:

You can use the following c# code to remove permission if you no longer need an unique permission on particular list item.
public static void RemoveItemLevelPermission()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        var web = ctx.Web;
        ctx.Load(ctx.Web, a => a.Lists);
        ctx.ExecuteQuery();

        List list = ctx.Web.Lists.GetByTitle("TestDocLibrary");
        string document = "TestFile.txt";
        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml = "" + document + "";

        var items = list.GetItems(camlQuery);
        ctx.Load(items);
        ctx.ExecuteQuery();
        foreach (var item in items)
        {
            //var user_group = web.SiteGroups.GetByName("Site Members");
            var user_group = web.SiteUsers.GetByLoginName("i:0#.f|membership|admin@sptenant.onmicrosoft.com");
            item.RoleAssignments.GetByPrincipal(user_group).DeleteObject();
            ctx.ExecuteQuery();
        }
    }
}

Delete All Unique Permissions:

Sometimes you may want to remove all the explicit permissions from a list item and reset broken inheritance (recover inheritance). In this case, you can use the following csom code to delete all unique permissions and reset broken inheritance.
public static void ResetRoleInheritanceInListItem()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        var web = ctx.Web;
        ctx.Load(ctx.Web, a => a.Lists);
        ctx.ExecuteQuery();                

        List list = ctx.Web.Lists.GetByTitle("TestDocLibrary");
        string document = "TestFile.txt";
        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml = "" + document + "";

        var items = list.GetItems(camlQuery);
        ctx.Load(items);
        ctx.ExecuteQuery();
        foreach (var item in items)
        {
            item.ResetRoleInheritance();
            ctx.ExecuteQuery();
        }
    }
}
Read More...

Tuesday, 26 April 2016

Reset Unique Permissions (Reset Broken Inheritance) In SharePoint using CSOM - C#

Sometimes we may require to delete unique permissions and reset broken inheritance (recover inheritance) for a particular site, or list library, or list item. In this post, I am going to write C# code to reset stopped role inheritance using CSOM (Client Object Model).

Reset Role Inheritance of a Site

The following C# code reset the broken inheritance of a sharepoint site.
private static void ResetRoleInheritanceInSite()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta/sbeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        var site = ctx.Web;
        //Stop Inheritance from parent site
        site.ResetRoleInheritance();
        ctx.Load(site);
        ctx.ExecuteQuery();
    }
}

Reset Broken Inheritance of a List Library

The following C# code reset the broken inheritance of a sharepoint list library.
private static void ResetRoleInheritanceInList()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        var web = ctx.Web;
        ctx.Load(ctx.Web, a => a.Lists);
        ctx.ExecuteQuery();

        List list = ctx.Web.Lists.GetByTitle("TestDocLibrary");
        //Stop Inheritance from parent
        list.ResetRoleInheritance();
        list.Update();
        ctx.ExecuteQuery();
    }
}

Reset Unique Permissions for a List Item

The following C# code reset the broken inheritance for a sharepoint list document item.
private static void ResetRoleInheritanceInListItem()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        var web = ctx.Web;
        ctx.Load(ctx.Web, a => a.Lists);
        ctx.ExecuteQuery();                

        List list = ctx.Web.Lists.GetByTitle("TestDocLibrary");
        string document = "TestFile.txt";
        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml = "" + document + "";

        var items = list.GetItems(camlQuery);
        ctx.Load(items);
        ctx.ExecuteQuery();
        foreach (var item in items)
        {
            item.ResetRoleInheritance();
            ctx.ExecuteQuery();
        }
    }
}
Read More...

Break permission inheritance in SharePoint using csom via C#

Sometimes we may require a business need to grant or set explicit permission for a particular site or list library, or listitem. To add explicit permission, we need to first break the inheritance (stop inheriting permissions) of the particular object.

Break Permission Inheritance in Site

The following C# code break the inheritance for a sharepoint site and add explicit permission for a particular user or group with csom (client object model).
private static void BreakRoleInheritanceForSite()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta/sbeta";
    using (var ctx = new ClientContext(sitrUrl))
    {    
        var site = ctx.Web;
        //Stop Inheritance from parent site
        site.BreakRoleInheritance(false, false);
        ctx.Load(site);
        ctx.ExecuteQuery();

        var roleAssignments = site.RoleAssignments;
        //Use below line, if you want to give access to a Group
        //var user_group = web.SiteGroups.GetByName("Site Members");
        var user_group = site.SiteUsers.GetByLoginName("i:0#.f|membership|admin@sptenant.onmicrosoft.com");

        var roleDefBindCol = new RoleDefinitionBindingCollection(ctx);
        // Add Role Definition i.e Full Controls, Contribute or Read rights etc..
        roleDefBindCol.Add(site.RoleDefinitions.GetByType(RoleType.Contributor));
        roleAssignments.Add(user_group, roleDefBindCol);
        ctx.Load(roleAssignments);
        site.Update();
        ctx.ExecuteQuery();
    }
}

Break Permission Inheritance in List Library:

The following C# code break the inheritance for a list library.
private static void BreakRoleInheritanceForList()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        var web = ctx.Web;
        ctx.Load(ctx.Web, a => a.Lists);
        ctx.ExecuteQuery();

        List list = ctx.Web.Lists.GetByTitle("TestDocLibrary");
        //Stop Inheritance from parent
        list.BreakRoleInheritance(false, false);
        list.Update();
        ctx.ExecuteQuery();     
    }
}

Stop Permission Inheritance in List Item::

The following C# code stop the inheritance from parent for a particular list item.
private static void SetItemLevelPermissions()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        var web = ctx.Web;
        ctx.Load(ctx.Web, a => a.Lists);
        ctx.ExecuteQuery();

        List list = ctx.Web.Lists.GetByTitle("TestDocLibrary");
        string documentName = "TextFile.txt";
        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml = "" +documentName +
            "";
        var items = list.GetItems(camlQuery);
        ctx.Load(items, a => a.Include(i => i.HasUniqueRoleAssignments));
        ctx.ExecuteQuery();

        foreach (var listItem in items)
        {
            if (!listItem.HasUniqueRoleAssignments)
            {
                listItem.BreakRoleInheritance(false, false);
                ctx.ExecuteQuery();
            }
        }
    }
}
Read More...

Set List Item Level Permission using CSOM - C# in SharePoint

In this post, I am going to explain how to add SharePoint listitem level permissions programmatically by CSOM (Client Object Model) in C#. Sometimes we may have a business requirement to grant or set explicit permission for a particular list item. To add explicit permission, we need to first break the inheritance (stop inheriting permissions) of the particular document item, then we need to create Role Definition object (i.e Full Controls, Contribute or Read rights etc...), then need to add new RoleAssignment for user or group object and finally we need to update the ListItem object to finish the work.

You can use the following C# code to set sharepoint list item level permission for a particular user or group with csom (client object model).
public static void SetItemLevelPermissions()
{
    string sitrUrl = "https://sptenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        var web = ctx.Web;
        ctx.Load(ctx.Web, a => a.Lists);
        ctx.ExecuteQuery();

        List list = ctx.Web.Lists.GetByTitle("TestDocLibrary");
        string documentName = "TextFile.txt";
        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml = "" +documentName +
            "";
        var items = list.GetItems(camlQuery);
        ctx.Load(items, a => a.Include(i => i.HasUniqueRoleAssignments));
        ctx.ExecuteQuery();

        foreach (var listItem in items)
        {
            if (!listItem.HasUniqueRoleAssignments)
            {
                listItem.BreakRoleInheritance(false, false);
                ctx.ExecuteQuery();
            }

            var roleAssignments = listItem.RoleAssignments;
            //Use below line, if you want to give access to a Group
            //var user_group = web.SiteGroups.GetByName("Site Members");
            var user_group = web.SiteUsers.GetByLoginName("i:0#.f|membership|admin@sptenant.onmicrosoft.com");

            var roleDefBindCol = new RoleDefinitionBindingCollection(ctx);
            // Add Role Definition i.e Full Controls, Contribute or Read rights etc..
            roleDefBindCol.Add(web.RoleDefinitions.GetByType(RoleType.Contributor));
            roleAssignments.Add(user_group, roleDefBindCol);
            ctx.Load(roleAssignments);
            listItem.Update();                    
            ctx.ExecuteQuery();
        }
    }
}
Read More...