Sunday, August 30, 2015

SharePoint 2016 IT Preview Released

SharePoint 2016 IT preview has been released! Cloud first infrastructure, Large file support (10GB!), Durable links, Zero downtime on patching, App launcher, Cloud hybrid search are some new exciting features!!

You can download the SharePoint 2016 IT Preview at: http://www.microsoft.com/en-us/download/details.aspx?id=48712

As per Microsoft, SharePoint Server 2016 will become available in Q2 2016, with a public beta planned for Q4 2015:http://blogs.office.com/2015/04/16/sharepoint-server-2016-update/

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


Friday, August 28, 2015

Fix "The Standard View of your list is being displayed because your browser does not support running ActiveX controls."

Problem:
Datasheet view in SharePoint 2010 did not work with a message "The Standard View of your list is being displayed because your browser does not support running ActiveX controls." in IE11 browser!
The Standard View of your list is being displayed because your browser does not support running ActiveX controls

Solution:


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


Thursday, August 27, 2015

Update Calculated Column Formula in SharePoint List using PowerShell

Requirement: Update a Calculated Field's formula for a specific column of a list across entire site collection.

PowerShell to update calculated field formula in SharePoint:
This updates the site column's formula for all subsites in the site collection.
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

#Variables
$SiteURL = "http://intranet.crescent.com"
$ColumnName="Productivity"

#Iterate through each web in given site collection
$Webs = Get-SPSite $SiteURL | Get-SPWeb -Limit All | ForEach-Object {
    
    #Check if the column exists
    if($_.Fields.ContainsField($ColumnName))
    {
        $column = $web.Fields[$ColumnName]
        #Update calculated field formula
        $Column.Formula = "=(([PlannedEffort]/5)/ActualEffort)*8"
        $Column.update($true)
        write-host "Updated Calculated Field formula at $($_.URL)"
    }
}
Same code can be used for List level formulas as well.

PowerShell to Update Calculated Column formula in SharePoint List:
In an another case, we had to replace a field in the calculated column's formula for all sites.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Variables
$SiteURL = "http://intranet.crescent.com"
$ListName="Projects"
$ColumnName="Productivity"
$OldField="PlannedEffort"
$NewField="EstimatedHours"

#Iterate through each web in given site collection
$Webs = Get-SPSite $SiteURL | Get-SPWeb -Limit All | ForEach-Object {
    
    #Get the List
    $List = $_.Lists.TryGetList($ListName)

    If($List)
    {
        #Check if the column exists
        if($List.Fields.ContainsField($ColumnName))
        {
            $Column = $List.Fields[$ColumnName]
            #Update calculated field formula
            $Column.Formula = $Column.Formula.Replace($OldField,$NewField)
            $Column.update($true)
            write-host "Updated Calculated Field formula at $($_.URL)"
        }
    }
} 
PowerShell to Update Calculated Column Formula in SharePoint

Creating calculated field using PowerShell is in my another article: How to Add Calculated Column to SharePoint List using PowerShell

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


Find All Web Parts in Use in a SharePoint Site using PowerShell

Requirement: Generate a report to get the Inventory of all web parts in use in a SharePoint site collection.

PowerShell script to generate web parts in use:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Configuration parameters
$SiteURL = "http://intranet.crescent.com"
$ReportOutput="C:\Webparts-in-use.csv" 

$ResultCollection = @()

#Get All Subsites in a site collection and iterate through each
$Site = Get-SPSite $SiteURL
ForEach($Web in $Site.AllWebs)
{
    write-host Processing $Web.URL
    # If the Current Web is Publishing Web
    if ([Microsoft.SharePoint.Publishing.PublishingWeb]::IsPublishingWeb($Web))
    {
        #Get the Publishing Web 
        $PubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($Web)
                  
        #Get the Pages Library
        $PagesLib = $PubWeb.PagesList
     }
     else
     {
        $PagesLib = $Web.Lists["Site Pages"]
     }             
        #Iterate through all Pages  
        foreach ($Page in $PagesLib.Items | Where-Object {$_.Name -match ".aspx"}) 
        {
            $PageURL=$web.site.Url+"/"+$Page.File.URL
            $WebPartManager = $Page.File.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
                
            #Get All Web Parts data
            foreach ($WebPart in $WebPartManager.WebParts)
            {
                $Result = New-Object PSObject
                $Result | Add-Member -type NoteProperty -name "Site URL" -value $web.Url
                $Result | Add-Member -type NoteProperty -name "Page URL" -value $PageURL
                $Result | Add-Member -type NoteProperty -name "Web Part Title" -value $WebPart.Title
                $Result | Add-Member -type NoteProperty -name "Web Part Type" -value $WebPart.GetType().ToString()

                $ResultCollection += $Result
            }
        }
}
#Export results to CSV
$ResultCollection | Export-csv $ReportOutput -notypeinformation
This script gets all web parts in site collection and generates a report in CSV format.
web part usage report in sharepoint
How to find a specific Web part? Say you want to find all Bamboo web parts in you SharePoint environment. Simple, just change Line#34 to: foreach ($WebPart in $WebPartManager.WebParts | Where-Object { $_.GetType().ToString() -like "*bamboo*"} )

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


How to Create a Self-Signed SSL Certificate in IIS for SharePoint

Self-Signed certificates provides encryption between the two ends. Technically, self-signed certificate are signed with its own private key. Often they are used in ADFS configuration. We may also have to use self-signed certificates in DEV-Test environments and for evaluations purposes. Lets see how to create a self-signed certificate using IIS.
Never use self-signed certificate on production sites!
Let's see, how to create a self-signed certificate in IIS step by step:
  1. Open IIS Manager, Click on Server name in the Left navigation Tree, Open "Server Certificates" widget
  2. From the Right pane, Click on "Create Self-Signed Certificate" link
  3. Enter the details for your self-signed certificate. Click on "OK" to create self-signed certificate from IIS.
That’s all. You'll find the new self-signed certificate generated and listed in Server Certificates. By default, its validity is for 1 year with common name (Issued To) to the server name.

You can create a self-signed certificate using PowerShell:
New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname uat.crescent.com 

How to Bind SSL Certificate with SharePoint Web Application?
Now, our certificate is ready use! You can bind it with any web application or export-import it to secure trusted identity provider or while publishing service applications. Lets see how to bind the certificate with any SharePoint web applications.
  1. Open IIS >> Select your target web application
  2. From right pane, Select Bindings link. Click on "Add" button.
  3. Select the certificate you created in the previous step from the SSL certificate dropdown. 
You have to repeat these steps in all your web front ends and application servers.

How to establish a Trust by Importing the Certificate?
  • From SharePoint Central Administration > Navigate to Security > Manage Trust
  • Click New > Enter Name and specify the location for the certificate for "Root Certificate for the trust relationship" and Click OK.
You can achieve the same with PowerShell:
$Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("c:\SharePoint.cer ")
New-SPTrustedRootAuthority -Name "SharePoint Certificate" -Certificate $Cert

How to copy a certificate? Just double click on the Certificate from IIS, Go to details tab and click copy to file!

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


Wednesday, August 26, 2015

SharePoint 2013 Design Manager - Cannot Map Network Drive in Windows Server 2008/2012?

Problem: 
I was trying to map Master Page Gallery as network drive from Windows Server 2008 R2, but got this error message:
"Network Error: Windows cannot access <URL>. Check the spelling of the name. Otherwise, there might be a problem with your network. To try to identify and resolve network problems, click Diagnose. Error code: 0x80070043. The network name cannot be found.
sharepoint 2013 map network drive windows cannot access

Solution:
This is due to: "Desktop  Experience" feature not enabled on Windows Servers by default. To resolve this error, follow these steps:
  • Open Server Manager in Windows Server 
  • Click on "Features" node and then Click on "Add Feature" link.
  • Select "Desktop Experience" and click Next >> Next >>Install to complete the wizard.
    sharepoint design manager map network drive cannot access
Once rebooted, I was able to map my SharePoint 2013 master pages gallery to network drive successfully!

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


Monday, August 24, 2015

Get Current User Account Name, E-Mail using Javascript Client Object Model in SharePoint 2013

Get Current User Account Name, E-Mail in JavaScript Client Object Model
You can use this code in Content Editor/Script editor or anywhere in SharePoint artifacts like Pages, Page Layouts, Master pages or external Javascript files.

<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(getCurrentUser, "sp.js");

var currentUser;

function getCurrentUser(){
var ctx= new SP.ClientContext.get_current();
var web = ctx.get_web();
currentUser = web.get_currentUser();
ctx.load(currentUser);
ctx.executeQueryAsync(onSuccess, onFailure);
}

function onSuccess() {
alert(currentUser.get_title()); // Domain\Account 
alert(currentUser.get_email());
document.getElementById('userLogin').innerHTML = currentUser.get_loginName(); 
}

function onFailure() {
alert('request failed' + args.get_message() + '\n' + args.get_stackTrace());
}

</script>

<div>Currently Logged User:
    <span id="userLogin"></span>
</div>


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


Saturday, August 22, 2015

SharePoint Online: Get All Lists and Libraries using PowerShell CSOM

While working with SharePoint online, you may have to iterate through all lists in a site. Here is the PowerShell script to get all lists from SharePoint online.

PowerShell CSOM Script to get all lists and libraries from site:
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/sites/sales"
$UserName="salaudeen@crescent.com"
$Password ="Password goes here"
 
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))

Try { 
    #Set up the context
    $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) 
    $Context.Credentials = $credentials

    #Get All Lists
    $Lists = $Context.web.Lists
    $Context.Load($Lists)
    $Context.ExecuteQuery()

    #Iterate through each list in a site   
    ForEach($List in $Lists)
    {
        #Get the List Name
        Write-host $List.Title
    }
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}


SharePoint Online: PowerShell Script to Iterate through all lists and libraries: 
Now, Lets make this code into a re-usable function and get list and library from all sites and subsites of given site.

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/sites/sales"
$UserName="salaudeen@crescent.com"
$Password ="Password goes here"
 
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))

Try {
    #Function to Get all lists from the web
    Function Get-SPOList($Web)
    {
        #Get All Lists from the web
        $Lists = $Web.Lists
        $Context.Load($Lists)
        $Context.ExecuteQuery()

        #Get all lists from the web   
        ForEach($List in $Lists)
        {
            #Get the List Name
            Write-host $List.Title
        }
    }

    #Function to get all webs from given URL
    Function Get-SPOWeb($WebURL) 
    {
        #Set up the context
        $Context = New-Object Microsoft.SharePoint.Client.ClientContext($WebURL)
        $Context.Credentials = $Credentials

        $Web = $context.Web
        $Context.Load($web)
        #Get all immediate subsites of the site
        $Context.Load($web.Webs)  
        $Context.executeQuery()
 
        #Call the function to Get Lists of the web
        Write-host "Processing Web :"$Web.URL
        Get-SPOList $Web
 
        #Iterate through each subsite in the current web
        foreach ($Subweb in $web.Webs)
        {
            #Call the function recursively to process all subsites underneaththe current web
            Get-SPOWeb($SubWeb.URL)
        }
    }

    #Call the function to get all sites
    Get-SPOWeb $SiteUrl
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
Script Output:
powershell to get all lists in sharepoint online


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


Friday, August 21, 2015

How to Use ULS Log Viewer to Analyse SharePoint Errors

ULS logs are unavoidable in SharePoint administration and support. This post describes the basic usage of ULS log viewer to reveal actual error message in SharePoint 2013 environment.

Scenario: You got an E-mail from end-user saying: They received a typical "An unexpected error has occurred." page with some GUID, time stamp, etc. User forward the error screenshot to SharePoint support team.
How to get the detailed error message using ULS Viewer?
Here is how to use SharePoint ULS viewer.
  1. To start with, Download the ULS Viewer tool to your SharePoint Web front end server. Its a tiny application, no installation is required.
  2. Open ULS Viewer application. Click on File Menu >> Open From >> File. This opens the default LOGS folder of your SharePoint hive, "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\LOGS".  
    uls viewer sharepoint 2013 tutorial
  3. Select log file(s) based on the time stamp from the error page. You can select multiple Log files at once. 
  4. Once logs files are opened, apply the filter with your correlation GUID by clicking "Filter" icon from the toolbar. Here is mine. Set the correlation value to the GUID we received in the error screen.
    uls viewer sharepoint 2013 correlation id
  5. This filters all detailed error messages of the specific correlation ID.
    how to use uls viewer sharepoint 2013
Please note, this searches LOGS only with in the current web front end. If you have multiple web front end servers, you have to repeat this step in all servers of your SharePoint farm. To monitor live ULS logs, Use File >> Open From >> ULS (Ctrl + U) option!

You can also use PowerShell cmdlet Get-SPLogEvent to get error details from the correlation ID. Here is How to get detailed error from Correlation ID using PowerShell

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


Display List from Top Level Site to SubSite in SharePoint

Requirement: We have a announcement list in Top level site of a SharePoint 2013 site collection and wanted it to appear on each subsite!

Solution: Requirements to show Lists/Libraries from Root site to Sub-site or Sub-site to Root site is quite common. In short, the solution idea is: Export the List view web part to web part gallery (so that its stored on root site's web part gallery) and insert the web part to subsite pages wherever required. Here comes the detailed steps.
Tips: You can also use SharePoint Content Query web part (or Content Search Web Part) if you have publishing feature turned ON!

Step 1: Export the Source List View Web Part using SharePoint Designer 2013
  • Open your Site in SharePoint Designer, Navigate to Lists and Libraries node in the left navigation tree view. Click on the All Items view to open it in SharePoint designer.
    display a list or library from sharepoint subsite to the top level site
  • Go to Insert Tab, Click on Dataview and choose your Source List from the dropdown.
    display a list or library from sharepoint 2013 subsite to the top level site
  • Now click on Web Parts tab, Click on To Site Gallery button from the ribbon.
    show list from parent site to subsite
  • Provide a Name and description to the web part you export and click on OK.
    show library from subsite to parent site
  • You'll get a prompt: "Do you want this Web Part to always show list data from the current web site? If you select No, the web part will show data from the list at the path your list location, relative to the site in which it is used." Confirm "Yes" to the prompt.
This saves the list view webpart along with the list contents to the site collection web part gallery and you can insert it to any page with in the site collection.

Step 2: Insert the Web Part to Target Page(s):
  • Go to your Subsite (or target site), Click on Site Settings gear, Choose Edit Page
  • Under Insert Tab, Click on Web Part
  • Navigate to Miscellaneous tab, pick the web part you exported in step 1, and insert it to relevant section of your page.
    display subsite library from parent site to subsite
That's all! You'll get the list from the parent site and its content gets updated whenever there is a change made on the source. Please note, this method works only within the same site collection!

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


Friday, August 14, 2015

Query-Import SharePoint List to Excel using Data Source Connections

Have you ever had to query and import SharePoint list to Excel? or ever required to use SharePoint list as excel data source? Well, just follow these steps to excel data connection to use SharePoint list as excel data source:

Step 1: Create a SharePoint list view with desired columns and order:
Go to your SharePoint list, Create a new view matching your requirement by adding necessary columns to it.

Step 2: Use Export to Excel to generate Data Source Connection
Navigate to your SharePoint list view created in Step-1, Use "Export to Excel" button under "List" tab. This imports SharePoint list to Excel and establishes data source connection in Excel as below.
use sharepoint list as excel datasource
 Make sure you set the below properties to skip column width and preserve sort/filter/layout/formats.
excel data connection to sharepoint list
You can also set the data refresh when opening the file.
sharepoint list as excel data source

How to Refresh the Data?
All you have to do is, either right click on any data imported and click "Refresh" in the context menu or Click on "Refresh All" button under "Data" tab of Excel.

Once you click refresh, Your Excel sheet will be synced from SharePoint list (One way - from SharePoint list!)
query sharepoint list using excel
Fix data format in Lookup and People picker columns
When you import data from SharePoint list to Excel, It just imports the data in the same format SharePoint stores internally. Say for E.g. You'll see John Mathew;#157;#Omar Saad in people picker column.

Solution:
Lets create a custom function in VBA code to replace the format "Number#;" in People Picker, Lookup columns with regular expressions:
  • Go to Excel >> File >> Options >> Customize Ribbon >> Enable "Developer" check box under Customize the Ribbon. This adds a new tab "Developer" in the Ribbon. 
  • Click on "View Code" button under "Controls" group of Developer Tab. 
  • Click on Tools >> Add Reference >> Pick "" to add Regular Expressions library: Microsoft VBScript Regular Expressions 5.5
  • Right Click the VBAProject >> Insert >> Module. Insert the below code into the Module.
    Function xREPLACE(pattern As String, searchText As String, replacementText As String, Optional ignoreCase As Boolean = True) As String
        On Error Resume Next
        Dim RegEx As New RegExp
        RegEx.Global = True
        RegEx.MultiLine = True
        RegEx.pattern = pattern
        RegEx.ignoreCase = ignoreCase
        xREPLACE = RegEx.Replace(searchText, replacementText)
    End Function
    
  • Now, Create a new column in Excel, Say for E.g. You are going to properly format "Deal Lead" column, Enter the formula as:
    =xREPLACE("\#\d*;|#\d*|\d*;#",TRIM([Deal lead])," ")
  • You can hide the original column "Deal Lead" and Name your new columns similar to "Deal Lead", say "Deal leader" or add a . (dot) prefix.
  • Save the Excel file as "XLSM" format so that the code saved along with your Excel sheet.


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


Thursday, August 13, 2015

Clear Maintenance Mode to Unlock a Site Collection in SharePoint 2013

Problem: Another fine morning, SharePoint 2013 sites started displaying a message: "We apologize for any inconvenience, but we've made the site read only while we're making some improvements.". Same time, noticed a backup failure E-mail from the backup software!
sharepoint 2013 remove maintenance mode

Root Cause:
Since the Backup failure occurred, SharePoint placed the site to read-only mode. However, all options under "Site Collection Quotas and Locks" were disabled in SharePoint 2013 Central Administration site!

Solution: Clear maintenance mode using PowerShell
This is because, SharePoint site collection is set under maintenance mode. To clear maintenance mode in SharePoint, use this PowerShell script:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Site Collection URL
$SiteURL = "http://intranet.crescent.com/"

#Clear Maintenance mode
$Admin = new-object Microsoft.SharePoint.Administration.SPSiteAdministration($SiteURL)
$Admin.ClearMaintenanceMode()
This removes maintenance mode in SharePoint 2013. Read more about SharePoint 2013 Maintenance Window Notifications

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


How to Delete a Document Library in SharePoint using PowerShell

Task: Delete document library in SharePoint with PowerShell

Solution: To delete a document library in SharePoint, follow these steps:
  • Browse to your SharePoint Site
  • Click on Site Settings gear >> Site Contents
  • Click on "Remove" link from the context menu of the library. Alternatively, You can go to Library Settings >> Click on "Delete this document library" to remove a document library in SharePoint.
powershell delete document library sharepoint 2013
Now, there are scenarios where you want to utilize PowerShell to remove a document library in SharePoint, such as: SharePoint UI doesn't provide delete option, You want to delete libraries in bulk, etc. Here is the PowerShell to delete document library in SharePoint 2013.

Delete document library in SharePoint using PowerShell:
$WebURL="http://intranet.crescent.com/"
$LibraryName="Documents"

#Get Web and List objects
$web = Get-SPWeb $WebURL
$list = $web.Lists[$LibraryName]

#delete sharepoint document library using powershell 
$list.Delete()
This removes document library in SharePoint 2010 with PowerShell. While the above script is fairly simple and permanently deletes the given document library from SharePoint - without sending it to recycle bin, lets add some error handling and make it a re-usable function.

Delete SharePoint document library using PowerShell
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

#Custom function to delete SharePoint document library using powershell
Function Delete-SPDocLibrary
{
    param
    (
        [string]$WebURL  = $(throw "Please Enter the Web URL!"),
        [string]$LibraryName = $(throw "Please Enter the Library Name to delete!")
    )
    try {
        $ErrorActionPreference = "Stop"   

        #Get the Objects 
        $Web = Get-SPWeb $WebURL
        $Library = (Get-SPWeb $WebURL).Lists.TryGetList($LibraryName)
  
        if($Library)
        {
            #Set Allow Delete Flag
            $Library.AllowDeletion = $true
            $Library.Update()
 
            #delete document library from sharepoint using powershell - Send library to Recycle bin
            $Library.Recycle() | Out-Null
         
            #TO permanently delete a library, Use: 
            #$Library.Delete()
 
            Write-Host "Library: $($LibraryName) deleted successfully from: $($WebURL)" -f Green
        }
        else
        {
            Write-Host "Library: $($LibraryName) doesn't exist at $($WebURL)" -f Red
        }
    }
    catch { 
        write-host "Error Deleting Library..." $_.Exception.Message
    }
    finally {
        $ErrorActionPreference = "Continue"
        $web.Dispose() 
    }
}

#Call the function to delete library
Delete-SPDocLibrary "http://intranet.crescent.com/" "Documents"


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


Saturday, August 8, 2015

Create AD Security Group/Distribution List from All SharePoint Users of the Farm

Have you ever had to send out an E-mail to all SharePoint users of your SharePoint Farm? Ever wanted to create a global AD security group which comprises of all SharePoint users? Well, I'm sure, You will at some point of time. E.g. during scheduled maintenance, Grant access to a global site, etc. Your SharePoint farm may have multiple web applications with lot of users accessing it. We can't keep a AD group or distribution list in sync up to date with all SharePoint users, isn't it? But we can create a AD security group or distribution list on-demand which includes all users from the entire SharePoint farm. By this way, it will be more accurate and update.

The idea is: Loop through each web application-site-collection-site in SharePoint farm to retrieve and add members to a security group or distribution list in AD.

PowerShell script to Add All SharePoint Users to an AD Security Group:
Add-PSSnapin Microsoft.SharePoint.PowerShell –ErrorAction SilentlyContinue
Import-Module ActiveDirectory

#Variables
$ADGroup="SP13 Authors" #Existing AD Security Group
$ReportPath="D:\SP13_Users.csv"

#Get all Webs from Entire FARM
$WebsCollection = Get-SPWebApplication | Get-SPSite -Limit All | Get-SPWeb -Limit All

#Array to hold user data
$UserDataCollection = @() 

foreach($Web in $WebsCollection)
{
    #Get all users from web programmatically 
    $UsersColl = $Web.AllUsers  
 
    #Get all users E-mails
    foreach ($User in $UsersColl) 
    {
        if( ($User.IsDomainGroup -eq $false) -and ($user.Email.ToString() -ne ""))
            {
                $UserData = New-Object PSObject               
                $UserData | Add-Member -type NoteProperty -name "EmailID" -value $user.Email.ToString() 
                $UserDataCollection += $UserData
            }
    }
}
    #Remove duplicates
    $UserDataCollection = $UserDataCollection | sort-object -Property  {$_.EmailID } -Unique

    Write-host "Total Number of Unique Users found:"$UserDataCollection.Length
 
    #Export to CSV
    $UserDataCollection | Export-Csv -LiteralPath $ReportPath  -NoTypeInformation

 #Add each user to AD Group
 $UserDataCollection | ForEach-Object {
 #Get the user from Email id
 $UserEmail = $_.EmailID 
 $ADuser = Get-ADUser -filter { EmailAddress -eq $UserEmail }
 
 #Ignore Orphans
 if($ADuser -ne $null)
 {
                #Add User to AD Aroup 
  Add-ADGroupMember -Identity $ADGroup -Members $ADuser
 }
} 
Run this script once. It will fetch and add all SharePoint users to the given AD group. To make it distribution list, Head on to AD, Find and locate the AD Group, Go to its properties, Assign an Email and change the Group type to "Distribution" if you need DL instead of Security group.


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


Friday, August 7, 2015

How to Delete a Custom Permission Level in SharePoint using PowerShell

Requirement:
PowerShell to remove a permission level in SharePoint

SharePoint: PowerShell script to delete permission level
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

#Configuration parameters
$WebURL="https://portal.crescent.com/sites/Sales/"
$PermissionLevelName="Contribute without Delete"

#Get the Web
$Web = Get-SPWeb $WebURL

if($Web.RoleDefinitions[$PermissionLevelName] -ne $null)
{
 $Web.RoleDefinitions.Delete($PermissionLevelName)
 write-host "Permission level Deleted successfully!" -f Green
}
else
{
 write-host "Permission level Not Found!" -f Red
}
Do not delete any out of the box Permission level! E.g. "Contribute", "Full Control", etc


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


How to Save List as a Template using PowerShell in SharePoint

Requirement: Save SharePoint list as a template using PowerShell

How to Save List as template in SharePoint?
List templates in SharePoint provides great re-usability without having to recreate every single columns. Say for e.g. you may created a custom list (say: Projects) in a SharePoint site collection  with all relevant columns, Now you might want this list structure in other site collections, without recreating the list on every single site. To save a list or library as template:
  • Go to your SharePoint list >> Navigate to list settings by going to List tab on the ribbon and then List Settings.
  • Click on "Save list as Template" under Permissions and Management group.
  • Provide the name for template File and Template name
  • Choose the appropriate option for "include content" and Click OK.
    how to save list as template in sharepoint 2013
You will see "Operation Successful" page and your template will be uploaded to "List Template Gallery".

Generally, its a good idea to create list templates at top level site, so that any site underneath can utilize the template!

PowerShell Script to save list as a template:
Here is how to save list as template in SharePoint 2013 using PowerShell.
#Add SharePoint Snapin
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

#Configuration parameters
$WebURL="https://projects.crescent.com"
$ListName="Parent Projects"
$TemplateName="Parent Project Template"
$TemplateFileName="ParentProjectTemplate"
$TemplateDescription="Crescent Inc. Parent Project List Template"
$SaveData = $true

#Get the Web and List objects
$Web = Get-SPWeb $WebURL
$List = $Web.Lists[$ListName]

#Save List as Template
$List.SaveAsTemplate($TemplateFileName, $TemplateName, $TemplateDescription, $SaveData)
Write-Host "List Saved as Template!"
save list as template sharepoint 2013 using powershell

Now,  You can create a new list instance from the template saved: Create List from List Template in SharePoint using PowerShell

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


Custom 404 Page Not Found Error page for SharePoint 2013 Site Collections

SharePoint 2013 is shipped with a default "Page not found" Error page in "Pages" library in publishing Sites (http://intranet.crescent.com/Pages/PageNotFoundError.aspx) which works automatically when a user hits a non-existent URLs.


We can either customize this page or create our own page and set as a page not found error page. Here are the steps to create a custom 404 page not found error page:
  • Go to Site Contents, Pages Library and Create New Error Page
  • Customize the error page with your own styles and images
    sharepoint custom page not found 404 error
  • Use PowerShell script to set the new page as default page not found error page.
    $site = Get-SPSite "http://your-sharepoint-site-coll-url"
    $site.filenotfoundurl = "/Pages/PageNotFound.aspx" #Relative path

Using SharePoint Designer to set Custom Page not found error page:
You can also use SharePoint designer to set the custom page not found error page: Here is how:
  • Open your SharePoint 2013 Site in SharePoint Designer 2013
  • Select the Site object in the left side treeview, Click on Site Options button in the ribbon 
  • Assign the "vti_filenotfoundpage" property of the site to a Custom Error Page that you created.
    sharepoint 2013 replace page not found error page
  • Don't forget to hit Save button to commit your changes.
The above is applicable for setting  custom error page at site collection level. If you want to apply it at web application level, refer my another article: Custom 404 Page Not Found Error Page for SharePoint

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


Saturday, August 1, 2015

SharePoint Online: Add Site Collection Administrator using PowerShell

SharePoint site collection administrators have Full access rights to manage all sites under a site collection. When creating a site collection, Global Administrator or SharePoint Online Administrator will automatically become the primary site collection admin. A SharePoint online site collection can have several administrators, but only one primary administrator, unlike SharePoint on-premises.

Its possible to add multiple site collection admins for any SharePoint site collection. To add additional site collection administrator in SharePoint online, you must be either Global Administrator or SharePoint online Site Collection Administrator of the particular site collection.

SharePoint online add site collection administrator
  • Navigate to your SharePoint Online administration center (E.g. https://crescent-admin.sharepoint.com/_layouts/15/online/SiteCollections.aspx )
  • Select the site collection, Click on "Owners" button from the ribbon and then click on "Manage Administrators" menu item.
    sharepoint online powershell add site collection administrator
  • This brings "Manage Administrators" page where you can add multiple site collection administrators. Also provides the option to change primary site collection administrator.
    sharepoint online powershell set site collection administrator
  • Now you can add new admins into the Site Collection Administrators box.
  • Once you have added the new user press OK to save the changes and any new Site Collection Administrator will have full rights to every site and sub-site within that Site Collection
Alternatively, Once the site collection is created, You can also navigate to Site Settings >> Site collection administrators link to add additional site collection administrators.
sharepoint online add site collection administrator powershell

Quite easy, isn't it? Well, Its easy for one single site collection. However there is a problem when you have large number of site collections. Say, you have 100's of SharePoint online site collections, You can't simply select all of your site collections and add a site collection administrator to all of them at one shot!

In SharePoint Online, site collection administrators to be added on a site collection by site collection basis, as there is no web application level users policies can be set from Central Administration as we do in SharePoint on-premises.

So, the solution is: Using PowerShell to add site collection administrator in SharePoint online!

PowerShell Script to Add Site Collection Administrator in SharePoint Online:
Here is the PowerShell for SharePoint online to add site collection administrator
#Variables for processing
$AdminURL = "https://crescent-admin.sharepoint.com/"
$AdminName = "salaudeen@crescent.onmicrosoft.com"
$SiteCollURL = "https://crescent.sharepoint.com/sites/Sales/"
$SiteCollectionAdmin = "mark@crescent.onmicrosoft.com"

#User Names Password to connect 
#$SecurePWD = read-host -assecurestring "Enter Password for $AdminName" 
$SecurePWD = ConvertTo-SecureString "Password1" –asplaintext –force  
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $SecurePWD
 
#Connect to SharePoint Online
Connect-SPOService -url $AdminURL -credential $Credential

#Add Site collection Admin
Set-SPOUser -site $SiteCollURL -LoginName $SiteCollectionAdmin -IsSiteCollectionAdmin $True

Add Site collection Admin to All SharePoint Online Sites using PowerShell:
SharePoint online PowerShell to add site collection administrator for all site collections.

#Variables for processing
$AdminURL = "https://Crescent-admin.sharepoint.com/"
$AdminName = "SPAdmin@Crescent.com"
 
#User Names Password to connect 
$Password = Read-host -assecurestring "Enter Password for $AdminName" 
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Password

#Connect to SharePoint Online
Connect-SPOService -url $AdminURL -credential $Credential

$Sites = Get-SPOSite -Limit ALL

Foreach ($Site in $Sites)
{
    Write-host "Adding Site Collection Admin for:"$Site.URL
    Set-SPOUser -site $Site -LoginName $AdminName -IsSiteCollectionAdmin $True
}
To Remove a Site Collection Admin, use Set-SPOUser cmdlet with -IsSiteCollectionAdmin $false parameter!

Change Primary Site Collection Administrator using PowerShell:
SharePoint Online PowerShell to set site collection administrator
#Variables for processing
$AdminURL = "https://crescent-admin.sharepoint.com/"
$AdminName = "salaudeen@crescent.onmicrosoft.com"
$SiteCollURL = "https://crescent.sharepoint.com/sites/Sales"
$NewSiteAdmin = "mark@crescent.onmicrosoft.com"

#User Names Password to connect 
$SecurePWD = ConvertTo-SecureString "Password1" –asplaintext –force  
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $SecurePWD
 
#Connect to SharePoint Online
Connect-SPOService -url $AdminURL -credential $Credential

#Change Site Collection Primary Admin
Set-SPOSite -Identity $SiteCollURL -Owner $NewSiteAdmin -NoWait

Related Articles:


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


You might also like:

Related Posts Plugin for WordPress, Blogger...