Reset unique permission for SharePoint document library and files

Sometime we need to reset the unique permission for document library, sub folders and files. If the document library has only 1-2 documents then we can handle it manually, but if you have thousands of files and folder so its quite difficult to reset it for all one by one. Below piece of code can help to reset unique permission for document library and its content. This script will take the top level permission from document library.


function ResetUniquePermission {
Param(
[Parameter(Mandatory = $true, HelpMessage="Enter the site url")][ValidateNotNullorEmpty()][string] $SiteURL ,
[Parameter(Mandatory = $true, HelpMessage="Enter the library name")][ValidateNotNullorEmpty()][string] $LibraryName,
[Parameter(Mandatory = $true, HelpMessage="Total number of files")][ValidateNotNullorEmpty()][int] $TotalFiles

)

$Web = Get-SPWeb $SiteURL 
$List= $Web.Lists[$LibraryName]
$Query = New-Object Microsoft.SharePoint.SPQuery
$Query.ViewXml =  @"
<View Scope="RecursiveAll">
    <Query>
        <OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
    </Query>
    <RowLimit Paged="TRUE">$TotalFiles</RowLimit>
</View>
"@;

$Items = $List.GetItems($Query)
for($j=0;$j -lt $Items.Count ;$j++)
{
    $Items[$j].ResetRoleInheritance()
    Write-Host "Permission reset done for file "$Items[$j]["Title"] -ForegroundColor Green
}
}

Export SharePoint List schema to CSV file

In this article I am going to demonstrates How to Export SharePoint custom list schema to CSV file. This example applies to SharePoint 2010 and SharePoint 2013 environment.


[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$listName="DemoList";
$siteURL="http://localhost/";
$csvPath="C:PowerOutput"+ $listName + ".csv";
$oSite= New-Object Microsoft.SharePoint.SPSite($siteURL)
$oWeb=$oSite.OpenWeb()
$oList=$oWeb.Lists[$listName]
#Get only custom fields which are created by user
$oList.Fields | ?{$_.CanBeDeleted -eq $true -and $_.Hidden -eq $false} | select Title,Internalname,Type |Sort-Object title| Export-Csv -Path $csvPath -Encoding ascii -NoTypeInformation
$oWeb.Dispose()
$oSite.Dispose()

PowerShell script to Upload multiple Custom List template and create custom list instances

I this article I am going to present you to create multiple SharePoint Custom list instances using PowerShell.It is very helpful when we are working on migrating SharePoint environment.

In below example list name is same as the template which we are uploading to template gallery.

Add-PSSnapin "Microsoft.SharePoint.PowerShell"

# Custom template path
$Path = "C:\CustomTemplate"

# Your site url
$oSite = Get-SPSite("htpp://localhost/")

# Get the root web
$oWeb = $oSite.RootWeb

# Get the list template gallery
$spLTG = $oWeb.GetFolder("List Template Gallery")

# Get the list template gallery Collection
$spcollection = $spLTG.files

# loop all stp files and upload/create custom list
Get-ChildItem $Path -Filter "*.STP" |
ForEach-Object {
$Templatefile = get-item $_.FullName
$catlogs="_catalogs/lt/" + $_.Name
$lstDesc="Description :" + $_.BaseName
$spcollection.Add($catlogs, $Templatefile.OpenRead(), $true)
$CustomlistTemplates = $oSite.GetCustomListTemplates($oWeb)
$oWeb.Lists.Add($_.BaseName, $lstDesc, $CustomlistTemplates[$_.BaseName])
Write-Host $_.BaseName+" List has been created" -foregroundcolor green
}

$oWeb.Dispose()
$oSite.Dispose()

Create custom permission level using C#,PowerShell and JSOM

Today,I am going to present you to create Permission level using C#, Powershell and JavaScript Object Model. Permission levels are predefined sets of permissions that you can assign to individual users, groups of users, or security groups, based on the functional requirements of the users and on security considerations.

Create Permission Level using C#

 public static void CreatePermissionLevel()
        {
            string strURL = "http://optimumview/";
            string CustomPermissionName = "myCustomPermissions";
            using (SPSite site = new SPSite(strURL))
            {
                using (SPWeb web = site.RootWeb)
                {
                    if (web.RoleDefinitions[CustomPermissionName] == null)
                    {
                        SPRoleDefinition role = new SPRoleDefinition();
                        role.Name = CustomPermissionName;
                        role.Description = "Description: It's only permission to ViewListItems,AddListItems and EditListItems";
                        //I'm using below permisson attributes in this code
                        //ViewListItems	View items in lists, documents in document libraries, and view Web discussion comments.
                        //AddListItems	Add items to lists, add documents to document libraries, and add Web discussion comments.
                        //EditListItems	Edit items in lists, edit documents in document libraries, edit Web discussion comments in documents, and customize Web Part Pages in document libraries.
                        role.BasePermissions = SPBasePermissions.ViewListItems | SPBasePermissions.AddListItems | SPBasePermissions.EditListItems;
                        web.RoleDefinitions.Add(role);
                        Console.WriteLine("Created Successfully!!");
                        Console.ReadLine();
                    }
                    else
                    {
                        Console.WriteLine("Permisson already exists!!");
                        Console.ReadLine();
                    }
                }
            }
        
        }

Click Here get list of Specifies the built-in permissions available in SharePoint Foundation.

Create Permission Level using Powershell

$spSite = Get-SPSite "http://optimumview/"
$spWeb = $spSite | Get-SPWeb
$customPermissionName="MyPowershellPermission"
if($spWeb.RoleDefinitions[$customPermissionName] -eq $null)
{
    $spRoleDefinition = New-Object Microsoft.SharePoint.SPRoleDefinition
    $spRoleDefinition.Name = $customPermissionName
    $spRoleDefinition.Description = "Description: It's only permission to ViewListItems,AddListItems and EditListItems";
    $spRoleDefinition.BasePermissions = "ViewListItems, AddListItems, EditListItems"
    $spWeb.RoleDefinitions.Add($spRoleDefinition)
	Write-Host $spRoleDefinition.Name "has been created successfully!!" -foregroundcolor green
}
else
{
	Write-Host "Permission already exists!!" -foregroundcolor red
}
$spWeb.Dispose()
$spSite.Dispose()

To get list of Specifies the built-in permissions available in SharePoint Foundation use below PowerShell Command :

[System.Enum]::GetNames("Microsoft.SharePoint.SPBasePermissions")

Create Permission Level using JavaSript

function createCustomPermisionLevel() {
        var clientContext = new SP.ClientContext.get_current();
        var oWeb = clientContext.get_web();
        var customPermissionName='MyJSOMPermission';
        // Set up permissions.
        var permissions = new SP.BasePermissions();
        permissions.set(SP.PermissionKind.viewListItems);
        permissions.set(SP.PermissionKind.addListItems);
        permissions.set(SP.PermissionKind.editListItems);
        // Create a new role definition.
        var roleDefinitionCreationInfo = new SP.RoleDefinitionCreationInformation();
        roleDefinitionCreationInfo.set_name(customPermissionName);
        roleDefinitionCreationInfo.set_description('Its only permission to ViewListItems,AddListItems and EditListItems');
        roleDefinitionCreationInfo.set_basePermissions(permissions);
        clientContext.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );

        function successHandler() {
            alert(customPermissionName +' : has been created sucessfully!');
        }

        function errorHandler() {
            alert("Request failed: " + arguments[1].get_message());
        }
    }

Click Here to get list of permission available in csom.

SharePoint List CRUD Operation using JavaScript

In order to my last post “SharePoint List CRUD Operation using PowerShell Management”. I am going to help you in learning how to do basic SharePoint List operations (CRUD – Create, Read, Update and Delete) using JavaScript.

Create SharePoint List item

function createSPListItem() {
        var listName = "DemoList"; //Give your list name
        var clientContext = new SP.ClientContext.get_current(); 
        var oWeb = clientContext.get_web();
        var oList = oWeb.get_lists().getByTitle(listName);

        var itemCreateInfo = new SP.ListItemCreationInformation();
        this.oListItem = oList.addItem(itemCreateInfo);
        this.oListItem.set_item("Title", "Test-Item-2");
        this.oListItem.set_item("DemoLocation", "India");
        this.oListItem.set_item("ProjectName", "CSR-RL-09");
        this.oListItem.update();

        clientContext.load(this.oListItem);
        clientContext.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );

        function successHandler() {
            alert('Item ' + this.oListItem.get_id() + 'created sucessfully!');
        }

        function errorHandler() {
            alert("Request failed: " + arguments[1].get_message());
        }
    }

Read SharePoint List item

    function readSPList() {
        var listName = "DemoList"; //Give your list name
        var clientContext = new SP.ClientContext.get_current();
        var oWebsite = clientContext.get_web();
        var oList = oWebsite.get_lists().getByTitle(listName);
        var camlQuery = new SP.CamlQuery();
        // set_viewXml function to define a CAML query and return items that meet specific criteria.
        // you can write caml query into below line
        camlQuery.set_viewXml('&lt;View&gt;&lt;RowLimit&gt;100&lt;/RowLimit&gt;&lt;/View&gt;');
        // The getItems(query) function enables you to define a Collaborative Application Markup Language (CAML) query that specifies which items to return
        this.collListItem = oList.getItems(camlQuery);

        clientContext.load(this.collListItem, "Include(Title, DemoLocation, ProjectName)");
        clientContext.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );

        function successHandler() {
            var listItemInfo;
            var listItemEnumerator;

            listItemEnumerator = this.collListItem.getEnumerator();

            listItemInfo = "";
            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();
                listItemInfo += "Title: " + oListItem.get_item('Title') + "&lt;br/&gt;" +
                "Location: " + oListItem.get_item('DemoLocation') + "&lt;br/&gt;" +
                "Project Name: " + oListItem.get_item('ProjectName') + "&lt;br/&gt;";
            }

            alert(listItemInfo);
        }

        function errorHandler() {
            resultpanel.innerHTML = "Request failed: " + arguments[1].get_message();
        }
    }
	

Update SharePoint List item

    function updateSPListItem() {
        var listName = "DemoList"; //Give your list name
        var clientContext = new SP.ClientContext.get_current();
        var oWeb = clientContext.get_web();
        var oList = oWeb.get_lists().getByTitle(listName);

        this.oListItem = oList.getItemById(1);
        this.oListItem.set_item("Title", "Test-Item-03");
        this.oListItem.set_item("DemoLocation", "SIG");
        this.oListItem.set_item("ProjectName", "NDR-PO-09");
        this.oListItem.update();

        clientContext.load(this.oListItem);
        clientContext.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );

        function successHandler() {
            alert('Item ' + this.oListItem.get_id() + 'updated sucessfully!');
        }

        function errorHandler() {
            alert("Request failed: " + arguments[1].get_message());
        }
    }
	

Delete SharePoint List item

    function deleteSPListItem() {
        var listName = "DemoList"; //Give your list name
        var clientContext = new SP.ClientContext.get_current();
        var oWeb = clientContext.get_web();
        var oList = oWeb.get_lists().getByTitle(listName);

        this.oListItem = oList.getItemById(1);
        this.oListItem.deleteObject();

        clientContext.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );

        function successHandler() {
            alert('Item ' + this.oListItem.get_id() + 'deleted sucessfully!');
        }

        function errorHandler() {
            alert("Request failed: " + arguments[1].get_message());
        }
    }
	

SharePoint List CRUD Operation using PowerShell Management

This post is going to help you in learning how to do basic SharePoint List operations (CRUD – Create, Read, Update and Delete) using SharePoint Management Shell or Windows PowerShell.

Lets open SharePoint Management Shell or open Windows PowerShell.When we are working on SharePoint Server there are two possibilities exists: either select the SharePoint Management Shell or Open Windows PowerShell.If We are using SharePoint Management Shell then SharePoint snap-in will already be installed.If you are using Standard PowerShell console, we can install the snap-in by entering the following command:

Add-PSSnapIn Microsoft.SharePoint.PowerShell

we can check the list of installed snap-in by using this command

Get-PSSnapIn

So, here is my list like below screenshot.

CRUDPowershell1

1) Create Item into SharePoint List

$webURL="http://optimumview"
$lstName="DemoList"
$oWeb=Get-SPWeb -Identity $webURL
$oList=$oWeb.Lists[$lstName]
$oListItem = $oList.items.add()
$oListItem["Title"]="Test-Item-0"
$oListItem["DemoLocation"]="US"
$oListItem["ProjectName"]="POW-JO-09"
$oListItem.Update()

2) Read single list item

$webURL="http://optimumview"
$lstName="DemoList"
$oWeb=Get-SPWeb -Identity $webURL
$oList=$oWeb.Lists[$lstName]
#To read single item uncomment below code
#$oListItem = $oList.GetItemById("1")
#Read multiple list item
$oListItem = $oList.Items | where {$_['ProjectName'] -like "IND1*"}
if($oListItem -ne $null)
{
$oListItem | ForEach-Object {
Write-Host $_['ID'] -foregroundcolor green
Write-Host $_['Title'] -foregroundcolor green
Write-Host $_['DemoLocation'] -foregroundcolor green
Write-Host $_['ProjectName'] -foregroundcolor green
}
}
else
{
Write-Host "No Items are found !!" -foregroundcolor red
}

3) Update SharePoint List item

#Update multiple list item

$webURL="http://optimumview"
$lstName="DemoList"
$oWeb=Get-SPWeb -Identity $webURL
$oList=$oWeb.Lists[$lstName]
$oListItem = $oList.Items | where {$_['ProjectName'] -like "IND*"}
if($oListItem -ne $null)
{
$oListItem | ForEach-Object {
$_['Title']="Test1" + $_['ID']
Write-Host "Item id:" $_['ID'] " has been updated!" -foregroundcolor green
$_.Update()
}
}
else
{
Write-Host "No Items are found !!" -foregroundcolor red
}

4) Deleting SharePoint List item

#Deleting multiple list item
$webURL="http://optimumview"
$lstName="DemoList"
$oWeb=Get-SPWeb -Identity $webURL
$oList=$oWeb.Lists[$lstName]
$oListItem = $oList.Items | where {$_['ProjectName'] -like "GLT*"}
if($oListItem -ne $null)
{
$oListItem | ForEach-Object {
$_.Delete()
Write-Host "Item id:" $_['ID'] " has been Deleted!" -foregroundcolor green
}
}
else
{
Write-Host "No Items are found !!" -foregroundcolor red
}

Hiding the Quick Launch in SharePoint 2013

  • Open and Edit SharePoint Page.
  • Add Script Editor or Content Editor Web part into anywhere in your page, and add the below code
<style>
//removes the Quick Launch
.ms-core-navigation { DISPLAY: none }
//Move all content of the page to left
#contentBox { margin-left: 0px }
</style>
  • Save the Page. The Quick Launch section should not be visible now.