Wednesday, 13 July 2016

whenCreated vs createTimeStamp

Both are Active Directory schema attributes which specifies the date and time of when an AD object was created. Both attributes return the same values, but the actual value is stored in whenCreated attribute alone, because createTimeStamp is a constructed attribute and it reads the data from whenCreated attribute.

WhenCreated attribute was implemented first, and to be complaint with LDAP standards the createTimeStamp was added later on as constructed attribute, the data is really stored only once in the Active Directory database.

Both attributes are replicated to all DC's, the createTimeStamp should not be replicated to the Global Catalog server since the isMemberOfPartialAttributeSet property of the attribute is not TRUE. However, you can also get a value from the GC.

Sources:

whenCreated vs createTimeStamp
Active directory attributes - createTimeStamp & whenCreated
Read More...

Tuesday, 12 July 2016

UserAccountControl Attribute Flag Values - Active Directory

UserAccountControl attribute is bitwise attribute and it control the behavior of the AD user and computer account.

This attribute value can be zero or a combination of one or more of the following values.

Property flagValue in hexadecimalValue in decimal
SCRIPT0x00011
ACCOUNTDISABLE0x00022
HOMEDIR_REQUIRED0x00088
LOCKOUT0x001016
PASSWD_NOTREQD0x002032
PASSWD_CANT_CHANGE
Note You cannot assign this permission by directly modifying the UserAccountControl attribute. For information about how to set the permission programmatically, see the "Property flag descriptions" section.
0x004064
ENCRYPTED_TEXT_PWD_ALLOWED0x0080128
TEMP_DUPLICATE_ACCOUNT0x0100256
NORMAL_ACCOUNT0x0200512
INTERDOMAIN_TRUST_ACCOUNT0x08002048
WORKSTATION_TRUST_ACCOUNT0x10004096
SERVER_TRUST_ACCOUNT0x20008192
DONT_EXPIRE_PASSWORD0x1000065536
MNS_LOGON_ACCOUNT0x20000131072
SMARTCARD_REQUIRED0x40000262144
TRUSTED_FOR_DELEGATION0x80000524288
NOT_DELEGATED0x1000001048576
USE_DES_KEY_ONLY0x2000002097152
DONT_REQ_PREAUTH0x4000004194304
PASSWORD_EXPIRED0x8000008388608
TRUSTED_TO_AUTH_FOR_DELEGATION0x100000016777216
PARTIAL_SECRETS_ACCOUNT0x04000000  67108864

Note: In a Windows Server 2003-based domain, LOCK_OUT and PASSWORD_EXPIRED have been replaced with a new attribute called ms-DS-User-Account-Control-Computed. For more information, check this article:https://msdn.microsoft.com/en-us/library/ms677840.aspx.

All the information available in Microsoft KB Article: https://support.microsoft.com/en-in/kb/305144

UserAccountControl flag descriptions:

  • SCRIPT - The logon script will be run.
  • ACCOUNTDISABLE - The user account is disabled.
  • HOMEDIR_REQUIRED - The home folder is required.
  • PASSWD_NOTREQD - No password is required.
  • PASSWD_CANT_CHANGE - The user cannot change the password. This is a permission on the user's object. For information about how to programmatically set this permission, visit the following Web site:
  • ENCRYPTED_TEXT_PASSWORD_ALLOWED - The user can send an encrypted password.
  • TEMP_DUPLICATE_ACCOUNT - This is an account for users whose primary account is in another domain. This account provides user access to this domain, but not to any domain that trusts this domain. This is sometimes referred to as a local user account.
  • NORMAL_ACCOUNT - This is a default account type that represents a typical user.
  • INTERDOMAIN_TRUST_ACCOUNT - This is a permit to trust an account for a system domain that trusts other domains.
  • WORKSTATION_TRUST_ACCOUNT - This is a computer account for a computer that is running Microsoft Windows NT 4.0 Workstation, Microsoft Windows NT 4.0 Server, Microsoft Windows 2000 Professional, or Windows 2000 Server and is a member of this domain.
  • SERVER_TRUST_ACCOUNT - This is a computer account for a domain controller that is a member of this domain.
  • DONT_EXPIRE_PASSWD - Represents the password, which should never expire on the account.
  • MNS_LOGON_ACCOUNT - This is an MNS logon account.
  • SMARTCARD_REQUIRED - When this flag is set, it forces the user to log on by using a smart card.
  • TRUSTED_FOR_DELEGATION - When this flag is set, the service account (the user or computer account) under which a service runs is trusted for Kerberos delegation. Any such service can impersonate a client requesting the service. To enable a service for Kerberos delegation, you must set this flag on the userAccountControl property of the service account.
  • NOT_DELEGATED - When this flag is set, the security context of the user is not delegated to a service even if the service account is set as trusted for Kerberos delegation.
  • USE_DES_KEY_ONLY - (Windows 2000/Windows Server 2003) Restrict this principal to use only Data Encryption Standard (DES) encryption types for keys.
  • DONT_REQUIRE_PREAUTH - (Windows 2000/Windows Server 2003) This account does not require Kerberos pre-authentication for logging on.
  • PASSWORD_EXPIRED - (Windows 2000/Windows Server 2003) The user's password has expired.
  • TRUSTED_TO_AUTH_FOR_DELEGATION - (Windows 2000/Windows Server 2003) The account is enabled for delegation. This is a security-sensitive setting. Accounts that have this option enabled should be tightly controlled. This setting lets a service that runs under the account assume a client's identity and authenticate as that user to other remote servers on the network. 
  • PARTIAL_SECRETS_ACCOUNT - (Windows Server 2008/Windows Server 2008 R2) The account is a read-only domain controller (RODC). This is a security-sensitive setting. Removing this setting from an RODC compromises security on that server.
Read More...

Tuesday, 5 July 2016

How to call a function in a ps1 file from powershell

In Powershell world, the user defined function is one of the easiest way to reuse the set of powershell commands. In some scenarios, this function might be too big, so having functions in separate ps1 file and load a function by importing .ps1 file is a good choice. In this post, I am going to explain how to import a powershell function from ps1 file.

Load Powershell function from ps1 file:

You just imagine the ps1 file MyScript.ps1, and the file contains the following content:
Write-Host "Loading functions"
function MyFunc
{
    Write-Host "MyFunc is running!"
}
Write-Host "Done"
To register the function MyFunc, we need to run the .ps1 file with the dot(.) operator prefix.
 . C:\Scripts\MyScript.ps1
The dot operator is used to include script.
PS C:>  . C:\Scripts\MyScript.ps1
Loading functions
Done

PS C:\> MyFunc
MyFunc is running!

Import Powershell function from psm1 file:

We can also import a function from PSM1 file by using Import-Module command. The major advantage of using Import-Module is that you can unload them from the shell if you need to, and it keeps the variables in the functions from creeping into the shell. First, save the MyScript.ps1 as MyScript.psm1 and load the file by using below command.
Import-Module C:\Scripts\MyScript.psm1
PS C:\> Import-Module C:\Scripts\MyScript.psm1
Loading functions
Done
PS C:\> MyFunc
MyFunc is running!
Read More...

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