Thursday, 24 November 2016

Get all checked out files in SharePoint Library using CSOM

If you are in business need to find and get the list of all checked out documents from a sharepoint document library, we can easily achieve it by using client object model (csom) in C#.

The following C# code find and lists the files which are checkout by current user and all other users.
public static void GetAllCheckedOutFilesInLibrary() 
{ 
    string sitrUrl = "https://spotenant.sharepoint.com/sites/contoso"; 
    using (var ctx = new ClientContext(sitrUrl)) 
    { 
        //ctx.Credentials = 
        ctx.Load(ctx.Web, a => a.Lists); 
        ctx.ExecuteQuery(); 
 
        var listName = "Documents"; 
        List list = ctx.Web.Lists.GetByTitle(listName); 
        var items = list.GetItems( 
            new CamlQuery() {  
            ViewXml = @"<View Scope='RecursiveAll'><Query> 
            <Where><IsNotNull><FieldRef Name='File_x0020_Type' /></IsNotNull></Where> 
            </Query></View>"  
        }); 
        ctx.Load(items, a => a.IncludeWithDefaultProperties(item => item.File, item => item.File.CheckedOutByUser)); 
        ctx.ExecuteQuery(); 
        foreach (var item in items) 
        { 
            if (item.File.CheckOutType != CheckOutType.None) 
            { 
                Console.WriteLine("File: " + item["FileRef"].ToString().Split('/').LastOrDefault()); 
                Console.WriteLine("Checked-Out By: " + item.File.CheckedOutByUser.Title); 
                Console.WriteLine("Checked-Out User Email: " +item.File.CheckedOutByUser.Email); 
                Console.WriteLine("Last Modified: " + DateTime.Parse(item["Last_x0020_Modified"].ToString())); 
                Console.WriteLine("-----------------------"); 
                Console.WriteLine(""); 
            } 
        } 
    } 
}
In the above code first we are retrieving all the files and check every file if it is checked out or not, this method may takes some time to process large document library. So alternatively we can use filter in caml query itself and retrieve checked out files alone.
public static void GetAllCheckedOutFilesWithCamlQuery() 
{ 
    string sitrUrl = "https://spotenant.sharepoint.com/sites/contoso"; 
    using (var ctx = new ClientContext(sitrUrl)) 
    { 
        //ctx.Credentials = 
        ctx.Load(ctx.Web, a => a.Lists); 
        ctx.ExecuteQuery();  
 
        var listName = "Documents"; 
        List list = ctx.Web.Lists.GetByTitle(listName); 
        var files = list.GetItems(  
            new CamlQuery()  
            { 
            ViewXml = @"<View Scope='RecursiveAll'><Query> 
            <Where><IsNotNull><FieldRef Name='CheckoutUser' /></IsNotNull></Where> 
            </Query></View>" 
            }); 
        ctx.Load(files); 
        ctx.ExecuteQuery(); 
        foreach (var file in files) 
        { 
            Console.WriteLine("File: " + file["FileRef"].ToString().Split('/').LastOrDefault()); 
            Console.WriteLine("Checked-Out By: " + (file["CheckoutUser"] as FieldUserValue).Email); 
            Console.WriteLine("Last Modified: " + DateTime.Parse(file["Last_x0020_Modified"].ToString())); 
            Console.WriteLine("-----------------------"); 
            Console.WriteLine(""); 
        } 
    } 
} 
The above caml query retrieves documents which are checkout by all the users. If you want to get all the documents that are checked out by the current user then you can use the following caml query.
<Where>
<And>
<IsNotNull>
<FieldRef Name='CheckoutUser' />
</IsNotNull>
<Eq>
<FieldRef Name='CheckoutUser' />
<Value Type=’Integer’>
<UserID Type=’Integer’ />
</Value>
</Eq>
</And>
</Where>

Friday, 11 November 2016

Check if Office 365 user exists or not with Powershell

In this article I am going write powershell script to check if an Office 365 user exists or not with the Azure AD Powershell cmdlet Get-MsolUser. First run the below command to connect Office 365 Powershell module.
Import-Module MSOnline
$msolCred = Get-Credential
Connect-MsolService –Credential $msolCred
The below command checks if the given user account already exists in Office 365 or not. You can retrieve user by using ObjectId or UserPrincipalName of the user.
$upn = "alexd@MyTenant.onmicrosoft.com"
$User = Get-MsolUser -UserPrincipalName $upn -ErrorAction SilentlyContinue
If ($User -ne $Null) { 
"User exists in Azure AD" 
} Else {
"User not found in Azure AD"}
You need to use the parameter -ErrorAction SilentlyContinue to skip error when user not found, otherwise you will get the error message 'Get-MsolUser : User Not Found'.

Check if multiple Azure AD accounts are exists or not

First set list of user's userprincipalname as array object and enumerate the array to find user account in Office 365.
$users = @("alexd@MyTenant.onmicrosoft.com","sarad@MyTenant.onmicrosoft.com","kevin@MyTenant.onmicrosoft.com")
foreach ($user in $users) {
$userobj = Get-MsolUser -UserPrincipalName $user -ErrorAction SilentlyContinue
If ($userobj -ne $Null) {
    Write-Host "$user already exists" -foregroundcolor "green"
} else {
    Write-Host "$user not found " -foregroundcolor "red"
}}

Thursday, 10 November 2016

Check if AD user exists with PowerShell

In this article I am going write powershell commands to check if an Active Directory user exists or not with the AD Powershell cmdlet Get-ADUser. First run the below command to import the Active Directory module.
Import-Module ActiveDirectory
The below command checks if the given user account exists in AD or not. You can identify a user by its distinguished name (DN), GUID, SID,SamAccountName or Name.
$Name = "kevin"
$User = $(try {Get-ADUser $Name} catch {$null})
If ($User -ne $Null) { 
"User exists in AD" 
} Else {
"User not found in AD"}
You need to use try-catch block to skip error when user not found, otherwise you will receive the error message 'Get-ADUser : Cannot find an object with identity'.

Find if multiple AD users are exists or not

We can set list of user names as array object and enumerate the users to find user account in AD.
$users = @("kevin","smith","nick")
foreach ($user in $users) {
$userobj = $(try {Get-ADUser $user} catch {$Null})
If ($userobj -ne $Null) {
    Write-Host "$user already exists" -foregroundcolor "green"
} else {
    Write-Host "$user not found " -foregroundcolor "red"
}}

Tuesday, 1 November 2016

Check if AD Users from OU are Member of a Group using Powershell

We can use the Active Directory powershell cmdlet Get-ADGroupMember to check if an AD user is member of an AD group. In this article, I am going to write powershell script to find if users of specific OU are member of a Group.

Run the following command to import Active Directory cmdlets.
Import-Module ActiveDirectory

Find AD Users from OU are Member of a Group:

We can use the cmdlet Get-ADUser to get AD users from specific OU and enumerate the users to check their membership in the particular group. We can use the parameter -Recursive with Get-ADGroupMember cmdlet to get nested group members along with direct group members. The following powershell command select users from the Organization Unit 'TestOU' and check the users are member of 'Domain Admins' group.
$users = Get-ADUser -Filter * -SearchBase "OU=TestOU,DC=TestDomain,DC=com"
$group = "Domain Admins"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty Name
$users | ForEach-Object {
$user = $_.Name
If ($members -contains $user) {
      Write-Host "$user exists in the group"
} Else {
      Write-Host "$user not exists in the group"
}}

Check if Single User is Member of a Group:

The following powershell command find if particular single user is member of 'Domain Admins' group.
$user = "TestUser"
$group = "Domain Admins"
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty Name

If ($members -contains $user) {
      Write-Host "$user exists in the group"
 } Else {
        Write-Host "$user not exists in the group"
}