Monday, November 30, 2015

Remove Field from View using PowerShell in SharePoint

In SharePoint, If you want to remove field from view programmatically using PowerShell, Here you go:

SharePoint delete column from view using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

#Function: sharepoint powershell delete field from view
Function Remove-FieldFromView([Microsoft.SharePoint.SPList]$List, [String]$ViewName, [string]$FieldInternalName)
{
    #Get the view
 $View = $List.Views[$ViewName]
    #To Get the Default View: List.DefaultView
    
    if($view -eq $Null) {write-host "View doesn't exists!" -f Red; return}
    
    #Check if view has the specific field already!
    if($view.ViewFields.ToStringCollection().Contains($FieldInternalName))
    {
        #Remove field from view: 
        $View.ViewFields.delete($FieldInternalName)
     $View.Update()
     write-host "Field Removed from the View!" -f Green
    }
    else
    {
    write-host "Field Doesn't Exists in the view!" -f Red
    }
}

#configuration parameters
$WebURL="https://portal.crescent.com/projects/"
$ListName="Project Milestones"
$ViewName="All Items"
$FieldName="ProjectDescription"

#Get the Web and List
$Web= Get-SPWeb $WebURL
$List = $web.Lists.TryGetList($ListName)

#Call the function to remove column from view 
Remove-FieldFromView $List $ViewName $FieldName

This PowerShell script removes given field from the given view.

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


Create Content Type Hub in SharePoint 2013

What is Content Type Hub SharePoint 2013?
Content Type Hub is a centralized repository of SharePoint Content types where we can manage and publish content types. Any Web application that subscribed to this content type hub can consume content types from this store. Content type hub is associated with the help of Managed Metadata Service Application.

Why we need content type hub in SharePoint?
Well, content types are limited within site collection scope. When you have a requirement to consume content types beyond site collection boundary, or even between different SharePoint farms (E.g. Dev-UAT-Production) - Content type hub is the answer! Without content type hub, You'll end up creating same content type again and again on all of the site collections - I'm sure this situation is pretty common in your  organization.

How to configure content type hub SharePoint 2013?
Content Type Hub is actually a Site Collection. You can either create a dedicated web application and then a top level site collection in it or create a separate site collection in any existing web application. Technically, You can choose any existing site collection and make it as a content type hub, however, as a best practice, lets create a dedicated site collection explicitly for content type hub.
Content type should be created/modified on the content type hub site collection and published to push the changes to all subscribed sites!

Create a content type hub SharePoint 2013:
Creating a new Content Type Hub is really a simple process. As the best practice says: Use explicit site collection for content type hub, Lets create an explicit managed path for content type hub.
  • Go to SharePoint 2016 Central Administration site
  • Application Management >> Select the Web application from the list, Click on "Managed Path" button from the ribbon.
    setting up content type hub sharepoint 2013
  • Add a new path "CtypeHub", choose the Type as "Explicit Inclusion" and click on "Add Path" button.
    content type hub sharepoint 2013 web application
  • As stated already, you can just create a new site collection inside any existing web application. the above step is completely options. Alright, lets create a site collection on the managed path we created. Go to: Application Management >> Create site collections 
  • Select the web application , provide a Title for the content type hub site collection, select the Web site address as "CtypeHub" 
    create a content type hub sharepoint 2013
  • Scroll down and select Template as "Team Site", select Site Administrators,etc. and click on "OK" to create content type hub.
Enable "Content Type Syndicate Hub Feature" for Content type Hub site Collection
  • Go to: Site Settings >> Site Collection Features under Site Collection Administration section.
  • Find the Content Type Syndication Hub Feature and Click on Activate Button to use this site as a Content Type Hub.
    how to configure content type hub sharepoint 2013
 Now, we have the content type hub ready. The next step is to associate it with Managed Metadata Service Application

Connect content type hub with Manage Metadata Service Application:
Lets Set up content type hub in Managed metadata service in Manage Service Applications from Central Administration.
  • Go to Central Administration >> click the Application Management >> under Service Applications, Select Managed Metadata Service >> Click on Properties from the ribbon.
  • In Managed metadata service application properties, Enter your Content Type Hub site collection URL in Content Type. In my case its: http://intranet.crescent.com/ctypehub
    how to setup content type hub in sharepoint 2013
  • Go back to Service Applications page, Select the Managed Metadata Service Connection >> Click on Properties from the ribbon, and set "Consume content type from the content type gallery"
    sharepoint 2013 content type hub step by step
That's all! We have completed setting up content type hub SharePoint 2013. Now your Content Type Hub Site Collection is registered with Managed Metadata Service Application. Content Type hub is available to all Lists or Libraries in the farm. Web applications can subscribe to this hub and pull down the published content types.

Last but not least: If you want to change content type hub URL in SharePoint, use PowerShell: Change content type hub URL in SharePoint 2013

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


Saturday, November 28, 2015

Cascading Dropdown in SharePoint List using Infopath Forms

What is Cascading drop downs? Well, Cascading drop downs are linked drop down controls where the content of the second drop down depends on the selection of the first one. E.g. When you Choose Country in the first drop down, the second drop down State is automatically filtered to the list of states actually in that county. Cascading drop downs are quite a common requirement and unfortunately, SharePoint doesn't support it Out of the box.

In this article, I'm documenting the implementation of cascading drop down functionality in SharePoint list forms using InfoPath forms step by step (at least for my own reference! even a simple mistake takes hours to resolve).

In short: You create a new data source to retrieve "Region" and "Country" columns from the Countries list and then filter the countries drop down to show only items matching with the "Region" selected in "Regions" drop down.

Cascading Drop down List Setup:
Here is my List setup:
  1. Regions - List of Regions - Parent List for Countries list's Region column.
  2. Countries -List of Countries with Region as lookup column from "Regions" list
  3. Projects List - List to capture project data, Where Region and Country columns are from above lists as lookup columns.

Step 1: Customize SharePoint List in InfoPath Designer

Open the Project SharePoint list in browser, Click on "Customized Form" button under List Tab. This opens your SharePoint list form in InfoPath Designer. Alternatively, You can open InfoPath Designer and Customize SharePoint List form. This establishes the data connections between SharePoint list and InfoPath.
infopath cascading dropdown from sharepoint list
BTW, To utilize InfoPath browser farms you need to have SharePoint Server Enterprise edition and "SharePoint Server Enterprise Site Collection features" feature activated at site collection level.

Step 2: Create New Data Connection:

Add new data connection in InfoPath to retrieve Country & its respective Region. 
  • In InfoPath Designer, Click on Data Tab, Click on Data Connections, Click on Add button
    infopath cascading drop down boxes
  • In Data Connection Wizard, Click on Receive data then on Next
    infopath cascading dropdown filter
  • Click on SharePoint Library or list and then on Next button
    sharepoint 2010 infopath forms cascading dropdown
  • Provide the URL of Countries List then on Next
    infopath cascading dropdowns in browser forms
  • Select the Countries list then on Next
    cascading dropdown in sharepoint 2010 infopath
  • Select the Country and Region fields, and click on Next
    cascading dropdown in sharepoint 2013 infopath
  • Provide a name to your data connection (say: Country) and click on Finish.
    sharepoint infopath cascading drop down lists

Step 3: Change the Data Source of the "Country" Drop down and Apply Filter:

Once we created the data source for Country,
  • Select the "Country" Drop Down in InfoPath form designer, Right Click and choose "Drop down List box Properties" to get the Control Properties window. 
  • In Data source dropdown, Select the new data source we created in Step 1 (In my case its: "Country"). Now, proceed to step.
    infopath cascading dropdown sharepoint list
Apply Filter to Country Drop down:
The Next step is to filter country values in the Country drop down based on the selected Region. 
  • In Entries section, click on the tree button. This brings Select Field or Group window.
    infopath 2010 cascading dropdown sharepoint list
  • Select the d:SharePointListItem_RW node under "DataFields" and click on Filter Data button.
  • In Filter Data window, click on Add button
  • In specify Filter Conditions, 
    • In the Country drop down, Add filter for Region. That is: Region from Countries data connection = Region from main data connection. since Region is a Lookup column – The matching rows will be retrieved. Here is how: In the first drop-down list choose "Region" field, Set the condition to: is equal to, in the next drop down choose: Select a field or group - This brings an another window to select the field.
    • Under "Fields" drop down, Change the drop down value from "Country(secondary)" to "Main".
    • Once you select "Main" in fields drop down, you'll get list of fields of the main data connection (In my case, its "Project:" list fields). Select the Region field from the list, and click on OK.
      Click on OK again to go back to the Country drop down properties window
Set Value and display Name Fields of Country Drop down:
Finally in the Country drop down properties, Set the Value and Display name fields to ID and Title respectively by selecting it through the tree button. This is because Country drop down is a lookup field and it stores lookup ID value internally. If you leave it as d:Title you will get an error when you try to save the list item.
sharepoint infopath cascading dropdown

Step 4: Add a Rule to "Regions" Drop down to Clear Countries Drop down on Re-selection:

This is important, because You'll have to clear the secondary cascading drop downs upon re-selection of primary drop down.
  • Select the Region Drop down in InfoPath designer, From the ribbon click on Add Rule, Select This Field Changes, Set a Field's value.
    infopath cascading dropdown from sharepoint list
  • Choose the field as "Country", leave the Value as blank and click OK.
    sharepoint 2010 infopath cascading dropdown
That's it! Now, from InfoPath Designer, Save and Publish the form!

There is a way to achieve cascading drop down functionality with SharePoint OOTB list forms and SPServices-Webservice-Javascript! Refer: Cascading Drop down In SharePoint Lists using jQuery

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


Friday, November 27, 2015

Create Word Automation Service Application using PowerShell in SharePoint 2016

The Word Automation Services Service Application provides developers a way to perform server-side conversion of documents that are supported by Microsoft Word (such as .doc, .docx, .rtf, etc) into other formats such as PDF,XPS, RTF, Docx,etc. In other words, Word Automation Services provides the "Save As" like functionality of the Microsoft Word client for SharePoint.

How to Create Word Automation Service Application using SharePoint 2016 Central Administration:
To create a Word Automation Service Application from SharePoint 2016 Central Administration site, Go to:
  • Application Management >> Manage Service Applications.
  • On the Service Applications tab, click New >> and then click Word Automation Services Application.
  • In the Create New Word Automation Services Application dialog box, Enter the Name, Application Pool, Select "Add to Default Proxy List" and click on next.
    sharepoint 2013 configure word automation service application
  • Enter the Database Server name and name of the database for word automation service application. Click Finish. 
    sharepoint 2016 create word automation service application powershell
  • Once created, The new instance of Word Automation Services appears in the list of service applications on the Service Applications tab.
PowerShell Script to Create Word Automation Service Application:
Use this PowerShell script to create word automation service application in SharePoint 2013/SharePoint 2016.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Configuration Parameters
$ServiceAppName = "Word Automation Service Application"
$AppPoolName = "Service Application App Pool"
$AppPoolAccount = "Crescent\SP16-ServiceAppPool"
$DBName = "SP16_WordAutomation_ServiceApp"
$DBServer="SP16-SQL"

Try {
    #Set the Error Action
    $ErrorActionPreference = "Stop"
  
    #Check if Managed account is registered already
    Write-Host -ForegroundColor Yellow "Checking if the Managed Accounts already exists..."
    $AppPoolAccount = Get-SPManagedAccount -Identity $AppPoolAccount -ErrorAction SilentlyContinue
    if($AppPoolAccount -eq $null)
    {
        Write-Host "Please Enter the password for the Service Account..."
        $AppPoolCredentials = Get-Credential $AppPoolAccount
        $AppPoolAccount = New-SPManagedAccount -Credential $AppPoolCredentials
    }
  
    #Check if the application pool exists already
    Write-Host -ForegroundColor Yellow "Checking if the Application Pool already exists"
    $AppPool = Get-SPServiceApplicationPool -Identity $AppPoolName -ErrorAction SilentlyContinue
    if ($AppPool -eq $null)
    {
        Write-Host -ForegroundColor Green "Creating Application Pool..."
        $AppPool = New-SPServiceApplicationPool -Name $AppPoolName -Account $AppPoolAccount
    }
  
    #Check if the Service application exists already
    Write-Host -ForegroundColor Yellow "Checking if Word Automation  Service Application exists already"
    $ServiceApplication = Get-SPServiceApplication -Name $ServiceAppName -ErrorAction SilentlyContinue
    if ($ServiceApplication -eq $null)
    {
        #There is no New-SPWordConversionServiceApplicationProxy, we can't therefore set it's name
        #The -default parameter adds the automatically created proxy to the default proxy group
        Write-Host "Creating $ServiceAppName Application & Proxy..."
        $ServiceApp = New-SPWordConversionServiceApplication -Name $ServiceAppName -ApplicationPool $AppPoolName -DatabaseName $DBName -DatabaseServer $DBServer -Default
    }
    
    #Start Service Instance(s)
    Write-Host -ForegroundColor Yellow "Starting the Word Automation Service Instance..."
    $ServiceInstance = Get-SPServiceInstance | where-object {$_.TypeName -eq "Word Automation Services"} | Start-SPServiceInstance
    
    Write-Host "Word Automation Service Application Created successfully!" -ForegroundColor Green
}
catch {
    Write-Host $_.Exception.Message -ForegroundColor Red
 }
 finally {
    #Reset the Error Action to Default
    $ErrorActionPreference = "Continue"
 }
  
There is no cmdlet for creating service application proxy for word automation service (such as: New-SPWordConversionServiceApplicationProxy. So the -Default switch in the above cmdlet adds the automatically created proxy to the default proxy group.

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


Thursday, November 26, 2015

How to Remove Content Database in SharePoint using PowerShell

SharePoint content databases are the most important artifacts in SharePoint platform as they hold majority of the data. However, at times we may have to delete the content database from SharePoint. Here is how you can utilize PowerShell to delete database:

SharePoint 2010: Remove content database using PowerShell
To delete content database from SharePoint, use: Remove-SPContentDatabase cmdlet, which removes the content database from SharePoint web application and deletes it from the SQL Server also.
Syntax:
Get-SPContentDatabase -Identity "ContentDB-Name" | Remove-SPContentDatabase

E.g. 
Get-SPContentDatabase -Identity "SP10_Intranet_Content02" | Remove-SPContentDatabase
sharepoint powershell delete content database
This deletes SharePoint Content database from SharePoint as well as from SQL Server permanently! As stated, use: Dismount-SPContentDatabase cmdlet if you want to remove the database from SharePoint alone!

Related Posts:


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


Sunday, November 22, 2015

Get/Set Hyperlink Field Values in SharePoint using PowerShell

Here is my PowerShell scripts to get and set hyperlink column values:

Get Hyperlink Field Value using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Configuration Variables
$SiteURL = "http://intranet.crescent.com/"
$ListName = "UserProfiles"
$FieldName="Picture"

#Get the Web, List Objects
$web = Get-SPWeb $SiteURL
$List = $Web.Lists.TryGetList($ListName)

If($list)
{
    foreach($Item in $List.Items)
    {
        #Get the Hyperlink column
        $Picture = New-Object Microsoft.SharePoint.SPFieldUrlValue($Item[$FieldName])
        #Get the URL of the Hyperlink
        $Picture.URL
        #Get the Decription - Title
        $Picture.Description
    }        
}
Update Hyperlink Field value using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Configuration Variables
$SiteURL = "http://intranet.crescent.com/"
$ListName = "UserProfiles"
$FieldName="Picture"

#Get the Web, List Objects
$web = Get-SPWeb $SiteURL
$List = $Web.Lists.TryGetList($ListName)

If($list)
{
    #Prepare the Hyperlink column
    $Picture = New-Object Microsoft.SharePoint.SPFieldURLValue
    $Picture.Description = "Profile Picture"
    $Picture.URL = "http://intranet.crescent.com/UserProfiles/Images/profile.jpg"
    
    #Add new List Item
    $Item = $List.AddItem()
    $Item[$FieldName] = $Picture
    $Item.Update()  
    
    Write-host "New Item Added Successfully!"
}


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


Friday, November 20, 2015

Export Document Library File-Folder-SubFolder Structure to CSV

Requirement:
Get the complete structure of all folders-subfolder-files from a SharePoint document library and export to CSV file.

PowerShell Script to Iterate through each folder and Sub-folder and get all files:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

#Custom Function to get all files of a folder
Function GetFiles-ByFolder([Microsoft.SharePoint.SPFolder]$Folder)
{
    write-host "Processing Folder:"$Folder.URL
    Foreach($File in $Folder.Files)
    {
        $content = $Folder.Name + "," + $Folder.URL +"," + $File.Name
        Add-content $OutPutFile $content
        Write-host $content
    }
}
 
#Variables
$WebURL="https://portal.crescent.com/sites/sales/"
$ListName="Team Docs"
$OutPutFile = "C:\LibraryFiles.csv"

#Delete the file if exists
If (Test-Path $OutPutFile) { Remove-Item $OutPutFile }

#Write CSV headers
Add-Content $OutPutFile "Root Folder, URL, File Name"

#Get site object
$Web = Get-SPWeb $WebURL
$List = $Web.Lists[$ListName]
$Folder = $List.RootFolder

#Call the function for Root folder
GetFiles-ByFolder $Folder

#Call the function for each subfolder - Excluding "Forms"
$folder.SubFolders | Where {$_.Name -ne "Forms" } | foreach-Object {
    #Call the function Recursively!
    GetFiles-ByFolder $_
}
This exports the inventory of all files and folders structure to a CSV file!

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


How to Add Managed Metadata Column to SharePoint List using PowerShell

Requirement: Add a Managed Metadata Column to SharePoint List using PowerShell.

PowerShell Script to Add Managed Metadata Column in SharePoint List:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 
 
#Variables
$WebURL="https://portal.crescent.com/sites/Sales/"
$ListName="Team Docs"
$FieldName="Region"
 
#Get the web and List
$Web = Get-SPWeb $WebURL    
$List = $Web.Lists[$ListName]

#Check if the column with same name exists in the list
if(!($List.Fields.ContainsField($FieldName)))
{
    #Get the Termset from Term store
    $TaxonomySession = Get-SPTaxonomySession -Site $web.Site
    $TermStore = $TaxonomySession.TermStores["Managed Metadata Service"]
    $TermGroup = $TermStore.Groups["Knowledge Portal"]
    $TermSet = $TermGroup.TermSets["Regions"]

    #Form the Taxonomy Field
    $TaxonomyField = $List.Fields.CreateNewField("TaxonomyFieldType", $TermSet.Name)
    $TaxonomyField.SspId = $TermSet.TermStore.Id
    $TaxonomyField.TermSetId = $TermSet.Id

    #Add the field to List
    $List.Fields.Add($TaxonomyField)
    $List.Update()
    
    Write-host "Managed Metadata column Added successfully!"
}
else
{
    Write-host "Managed Metadata column with the specific name already exists!" -f RED
}
Please note, You need to have MMS Service application up and running. Here
  • Managed Metadata Service - is the MMS application proxy name
  • Knowledge Portal  - is the name of the term set group
  • Regions - is the name of the term set
This Adds "Region" Metadata column to the given document library "Team Docs"
sharepoint powershell create managed metadata column
Tags: sharepoint powershell managed metadata column, powershell add managed metadata column to list, create managed metadata column powershell, create managed metadata field powershell

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


Tuesday, November 17, 2015

SharePoint Products Configuration Failed: Unable to create a Service Connection Point in the current Active Directory domain. Verify that the SharePoint container exists in the current domain and that you have rights to write to it.

Problem:
After applying a service pack, Ran SharePoint Products Configuration Wizard. It failed with this error message: "An exception of type microsoft.sharepoint.postsetupconfiguration.postsetupconfigurationtaskexception was thrown. additional exception information: Failed to upgrade SharePoint Products."
An exception of type microsoft.sharepoint.postsetupconfiguration.postsetupconfigurationtaskexception was thrown. additional exception information: Failed to upgrade SharePoint Products.

Tried Running the PSconfig upgrade using command line, but that too failed:
psconfig -cmd upgrade -inplace b2b -wait

On scanning the log file it generated, found this error message:
Unable to create a Service Connection Point in the current Active Directory domain. Verify that the SharePoint container exists in the current domain and that you have rights to write to it.

Solution:
Although, creating a service connection point container will resolve the problem, that require me to have Active Directory administrator rights! which is not possible In my case and we don't want to track SharePoint installations as of now!

So, What's the solution? Run this command line: 
psconfig -cmd upgrade -inplace v2v -passphrase "Type your Farm Pass Phrase" -wait
This time, upgrade completed successfully!

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


Sunday, November 15, 2015

How to Recover Credentials from Secure Store Service in SharePoint using PowerShell

So the previous SharePoint administrator left without documenting passwords from SharePoint secure store Service? Unfortunately, There is no way to get stored user name, passwords from SharePoint secure store service from Central Administration site.
Recover secure store service credentials in SharePoint using powershell

No worries, Lets use PowerShell to decrypt all user names and passwords stored in SharePoint secure store service.

PowerShell script to Get Credentials from Secure Store Service: 
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Any web application associated with SSS proxy application or central admin
$WebAppURL="http://intranet.crescent.com"

#Establish the Context
$Provider = New-Object Microsoft.Office.SecureStoreService.Server.SecureStoreProvider
$Provider.Context =  Get-SPServiceContext -Site $WebAppURL
 
#Get All Target Applications
$TargetApps = $provider.GetTargetApplications()
foreach ($App in $TargetApps)
{
    Write-Output $App.Name
    
    #Get the credentials for the App
    $Credentials = $provider.GetCredentials($App.Name)
    foreach ($Cred in $Credentials)
    {
        $EncryptString  = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($cred.Credential)
        $DecryptString  = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($EncryptString)
 
        Write-Output "$($cred.CredentialType): $($DecryptString)"
    }
 }


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


Saturday, November 14, 2015

Another component has already added an HTTPSessionState to the Context. Please make sure only one session state module should be registered

Problem: 
After changing web application properties from SharePoint central administration site to support "anonymous access", sites started giving this error message: Another component has already added an HTTPSessionState to the Context. Please make sure only one session state module should be registered
Another component has already added an HTTPSessionState to the Context. Please make sure only one session state module should be registered

Solution:
Open Web.config file of the SharePoint web application, search for  "SessionStateModule", Make sure only one entry exists under sections such as <httpModules> and <modules>. Comment out any other additional entries!


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


People Search relevance is not optimized when the Active Directory has errors in the manager reporting structure - SharePoint 2013 Health analyzer error

Problem: 
SharePoint 2013 Health analyzer logged this error - People Search relevance is not optimized when the Active Directory has errors in the manager reporting structure.
People Search relevance is not optimized when the Active Directory has errors in the manager reporting structure

Also in Windows Event Viewer, from MSSQL$SHAREPOINT Source, "An exception occurred while enqueuing a message in the target queue. Error: 15404, State: 11. Could not obtain information about Windows NT group/user , error code 0x534."

Root Cause: There are user profiles in Active directory with no "Manager" property value defined (empty!). SharePoint uses this field for features such as to determine colleagues, social, people search relevance,etc.

Solution: Set the Manager property value for all users who don't have it set! Here is the quick way to find a list of users who don't have Manager field:
Import-Module ActiveDirectory

Get-ADUser -Filter * | Where-Object {$_.Manager -Eq $Null} | Export-CSV D:\Profiles.csv -notype

Alternatively, although its not a good idea, you can disable this rule in SharePoint health monitor if you want to suppress these errors!

What if Users don't have Manager at all?
Say for e.g. by organization's structure, CxOs may not have manager, isn't it? If that's the case, you'll have to explicitly specify these users as company leaders. Here is how:
$UPSProxy = Get-SPServiceApplicationProxy | ? {$_.typename -eq "User Profile Service Application Proxy"}

Add-SPProfileLeader -ProfileServiceApplicationProxy $UPSProxy -Name "Domain\Username"

You can follow this technet article: https://technet.microsoft.com/en-us/library/hh867937%28v=office.14%29.aspx

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


Friday, November 13, 2015

How to Delete a Master Page in SharePoint using PowerShell

Requirement:
After deploying a new master page as part of new branding, We wanted to delete the old master page from all SharePoint sites. As we've applied the new master page, we don't want our existing custom master page to be appear in the master page gallery and master page selection page.

Solution:
PowerShell script to delete the SharePoint master page.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Site URL and Master page Name variables
$WebURL="https://portal.crescent.com/sites/sales/"
$MasterPageName="crescent.master"

#Get Objects
$web = Get-SPWeb $WebURL
$MasterPage = $web.GetFolder("_catalogs/masterpage").Files[$MasterPageName]

#Delete the Master page using PowerShell
$MasterPage.Delete();

write-host "Master page deleted!" 
This PowerShell script just deletes given master page from the given web. Loop through each web and delete the master page from all.

Remember, If the master page you are trying to delete is configured as either Default master page or custom master page, You can't delete it! change the master page in your code first and then try deleting it again.

Related post: Change Master Page 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


Sunday, November 8, 2015

Add Attachment to List Item in SharePoint using PowerShell

PowerShell script to add attachment to list item programmatically in SharePoint:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Custom Function to Add attachment to SharePoint List Item
Function Add-Attachment($Item, $AttachmentPath)
{
  $FileContent = [System.IO.File]::ReadAllBytes($AttachmentPath)
  $Item.Attachments.Add([System.IO.Path]::GetFileName($AttachmentPath), $FileContent)
  $Item.Update()
 
  Write-host "Attachment Added to List Item Successfully!"
}

#Variables
$SiteURL="https://portal.crescent.com/sites/Deals"
$ListName="Tasks"
$ItemID=1
$AttachmentPath="c:\Scripts\ASI-LOG.docx"

$web = Get-SPWeb $SiteURL
$List = $web.Lists[$ListName]
$Item = $list.GetItemById($ItemID)

#Call the function to Add Attachment
Add-Attachment $Item $AttachmentPath


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


Saturday, November 7, 2015

Copy Permission Levels in SharePoint using PowerShell

Requirement: Copy permission level in SharePoint 2013 using PowerShell

PowerShell to Copy permission level programmatically in SharePoint
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

#Configuration parameters
$WebURL="https://portal.crescent.com"
$SourcePermissionLevelName="Contribute"
$TargetPermissionLevelName="Contribute without Delete"

#Get the Source Permission Level
$SourcePermissionLevel = $Web.RoleDefinitions[$SourcePermissionLevelName]
#sharepoint copy permission level
$TargetPermissionLevel = New-Object Microsoft.SharePoint.SPRoleDefinition($SourcePermissionLevel)

#Remove "Delete" Base permission 
$TargetPermissionLevel.BasePermissions = "ViewListItems, AddListItems, EditListItems, OpenItems, ViewVersions, DeleteVersions, ManagePersonalViews, ViewFormPages, Open, ViewPages, CreateSSCSite, BrowseDirectories, BrowseUserInfo, AddDelPrivateWebParts, UpdatePersonalWebParts, UseClientIntegration, UseRemoteAPIs, CreateAlerts, EditMyUserInfo"

#Add the New Permission Level
$TargetPermissionLevel.Name= $TargetPermissionLevelName
#permission level description
$TargetPermissionLevel.Description="Contribute without Delete Permission Level"
$web.RoleDefinitions.Add($TargetPermissionLevel)
write-host "Permission level Copied successfully!"

The above PowerShell script copies permission level programmatically in SharePoint 2013/2010 and applies given base permissions. While it copies an existing permission level into a new permission level, How about copying permission level between site collections?

Copy Permission Level between site collections using PowerShell:
sAdd-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

Function Copy-PermissionLevel($SourceWebURL, $TargetWebURL, $PermissionLevelName)
{
 #Get the Webs
 $SourceWeb = Get-SPWeb $SourceWebURL
 $TargetWeb = Get-SPWeb $TargetWebURL
 
 #Check if given Source permission level exists
 if($SourceWeb.RoleDefinitions[$PermissionLevelName] -ne $null)
 {
  #Get the Source Permission Level
  $SourcePermissionLevel = $SourceWeb.RoleDefinitions[$PermissionLevelName]
  
  #Check if Target permission level name already exists!
  if($TargetWeb.RoleDefinitions[$PermissionLevelName] -eq $null)
  {
   #sharepoint copy permission level
   $TargetPermissionLevel = New-Object Microsoft.SharePoint.SPRoleDefinition($SourcePermissionLevel)
   #Add the New Permission Level
   $TargetWeb.RoleDefinitions.Add($TargetPermissionLevel)

   write-host "Permission level Copied successfully!" -f Green
  }
  else
  {
   write-host "Permission Level Already Exists!" -f Red
  }
 }
 else
 {
  write-host "Source Permission Level Not Found!" -f Red
 }
}

#Configuration Variables
$SourceURL="https://portal.crescent.com/"
$TargetURL="https://portal.crescent.com/sites/sales"
$PermissionLevelName="Contribute without Deletes"

#Call the function to copy permission level between site collections
Copy-PermissionLevel $SourceURL $TargetURL $PermissionLevelName
 


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


The password supplied with the username Domain\Username was not correct. Verify that it was entered correctly and try again.

Problem:
While trying to create a new web application from SharePoint 2013 central administration site, It gave this error message:

Sorry, something went wrong
The password supplied with the username Domain\Username was not correct. Verify that it was entered correctly and try again.
The password supplied with the username Domain\Username was not correct. Verify that it was entered correctly and try again.
Root Cause:
This issue arises  when the SharePoint 2013/SharePoint 2010 farm account's password is expired or changed!

Solution:
Update SharePoint Farm Credentials! Here is how to update SharePoint 2013 farm credentials using STSADM tool:
stsadm -o updatefarmcredentials -userlogin <UserAccount> -password <New-password>
 

E.g.
stsadm -o updatefarmcredentials -userlogin Crescent\SP13Farm -password "Password-of-the-Account"

Once you receive the message "Operation completed successfully.", Restart IIS!

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


How to Increase Distributed Cache Memory Size in SharePoint 2013

By default, the Distributed cache memory allocation size defaults to a value of 10% of total physical memory when SharePoint Server 2013 installs. The Distributed Cache service uses half of that memory allocation for data storage (also known as cache size, 5% cache size). You can change the memory allocation as it significantly affects the performance of the Distributed Cache service. Or you may want to change the memory allocation if you added more memory to your SharePoint servers after SharePoint is installed.

Get Distributed Cache Memory Allocation size:
To Get the current memory allocation of Distributed Cache, use:
Use-CacheCluster  
Get-AFCacheHostConfiguration -ComputerName $env:computername -CachePort "22233"  
Increase Distributed Cache Memory Size in SharePoint 2013
SharePoint 2013 distributed Cache is explained in my another article: Distributed Cache Service in SharePoint 2013 - Explained

How to Change  Distributed Cache Memory Size in SharePoint 2013? 
To Change distributed cache memory settings follow these steps:
  1. Stop the Distributed Cache service on all cache hosts in the farm.
  2. Change the cache size of the Distributed Cache service using: Update-SPDistributedCacheSize cmdlet
  3. Start the Distributed Cache service on all cache hosts in the farm
Step 1: Stop Distributed Cache Service:
Follow these steps on each host to stop distributed cache service.
  • Go to SharePoint 2013 Central Administration >> System Settings >> Manage services on server. 
  • Locate and Click on "Stop" link next to Distributed Cache.
You can also use PowerShell to stop Distributed Cache Service instance.
$instanceName ="SPDistributedCacheService Name=AppFabricCachingService" 
$serviceInstance = Get-SPServiceInstance | ? {($_.service.tostring()) -eq $instanceName -and ($_.server.name) -eq $env:computername} 
$serviceInstance.Unprovision()

#Or Use: Stop-SPDistributedCacheServiceInstance -Graceful

Step 2: Increase Distributed Cache Memory Size
You can increase size of the Cache with the following PowerShell Command. Login to any one of your SharePoint server which is part of Distributed cache cluster and run this command, it would set same Cache Size on all cache host on the farm including application servers if they are part of Cache cluster.
Update-SPDistributedCacheSize -CacheSizeInMB 1024
The maximum amount of memory that can be allocated to each cache host in the server farm is 16GB,  We cannot mention this value more than 40% of the system RAM. Ensure that the memory allocation assigned to the Distributed Cache service is the same on all servers that are running the Distributed Cache service. If you are running a small farm with <10k users in Collocated mode, 1 GB of RAM should be enough. For dedicated mode, use the formula given in the technet article below.

Step 3: Start the Distributed Cache service

Start the Distributed Cache service on each host using:
  • Central Administration >> System Settings >> Manage services on server.
  • Locate and Start Distributed cache service. 
Using PowerShell to Start Distributed Cache Service Instance:
$instanceName ="SPDistributedCacheService Name=AppFabricCachingService" 
$serviceInstance = Get-SPServiceInstance | ? {($_.service.tostring()) -eq $instanceName -and ($_.server.name) -eq $env:computername} 
$serviceInstance.provision()
Technet Reference: Manage the Distributed Cache service in SharePoint Server 2013

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


Friday, November 6, 2015

Distributed Cache Service in SharePoint 2013 - Explained

What is Distributed Cache in SharePoint 2013:
The SharePoint Distributed Cache service is an additional caching mechanism introduced in SharePoint 2013 to support beyond the options that already exist (such as Object Cache, BLOB Cache, and Page Output Cache) from the earlier versions of SharePoint. Distributed cache enables to quickly retrieve data without any dependency on SQL databases, as everything is stored in memory.

The Distributed Cache service provides caching services for several features in SharePoint Server 2013. Some of the features that use the Distributed Cache service include:
  • News feed
  • Authentication
  • OneNote client access
  • Security Trimming
  • Page load performance
How to Install SharePoint Distributed Cache?
The good news is: You don't have to do anything to get distributed cache service features! When you install SharePoint 2013, distributed cache gets installed and configured automatically! The Distributed Cache service is built on Windows Server AppFabric, which is a required component for SharePoint 2013 and is installed as part of the SharePoint 2013 prerequisite installer.

Distributed Cache service - Hosts - Cluster and Modes:
Any server in the farm running the Distributed Cache service is known as a cache host. A cache cluster is the group of all cache hosts in a SharePoint Server 2013 farm. A cache host joins a cache cluster when a new application server running the Distributed Cache service is added to the farm. When using a cache cluster, the Distributed Cache spans all application servers and creates one cache in the server farm. Distributed Cache service can be deployed in two modes:
  1. Dedicated mode
  2. Collocated mode.
When running in dedicated mode, the Distributed Cache service is started and all other services are stopped on the server. In collocated mode, the Distributed Cache service is running along with other services on the server. For large-scale production use, the recommendation is to have dedicated servers hosting your cache.  If you have over 10000 users, you should look into a dedicated server (dedicated mode) Distributed Cache.

Should I Start Distributed Cache Service in All Servers of the Farm?
The Distributed Cache is started and run on all WFE and APP servers by default. Running distributed cache on an already overtaxed server, such as SQL Server, Search services, Excel Services, or Project Services, negates any benefit you may garner out of distributed cache. As per Microsoft: When the Distributed Cache service runs on a server together with other services and the server's memory resources near 95% utilization, the Distributed Cache will start throttling requests. This means that the Distributed Cache service will no longer accept read and write requests until the server utilization reduces to approximately 70% utilization 

If your farm is having four or more servers, starting distributed cache service in all servers results performance degrade, as per this Technet article https://technet.microsoft.com/en-us/library/jj891124.aspx

Get Distributed Cache Cluster-Servers:
Use this cmdlets to retrieve current cache setup:
Use-CacheCluster
Get-CacheHost
This gets you the cache hosts, their ports, service status and version info.

How to Add Distributed Cache on a new server:
You can add a server to distributed cache host by running the cmdlet:
Add-SPDistributedCacheServiceInstance
Verify the distributed cache Service:
  • Go to: Central Administration >> Services on server >> Pick the relevant server >> Check Distributed cache service must be in Started state.
  • Open Windows Services console (services.msc) > Locate "AppFabric Caching service">> Make sure its Started.
Memory Allocation for Distributed Cache:
A minimum of 8 GB and maximum of 16 GB can be allocated to the Cache. On a server that has more than 16 GB of total physical memory, allocate a maximum of 16 GB of memory to the Distributed Cache service. By default, the Distributed memory allocation size defaults to a value of 10 percent of total physical memory when SharePoint Server 2013 installs. You can change the memory allocation with the Update-SPDistributedCacheSize cmdlet. This allocation significantly affects the performance of the Distributed Cache service. Ensure that the memory allocation assigned to the Distributed Cache service is the same on all servers that are running the Distributed Cache service

How to Stop Distributed Cache Service:
The Distributed Cache service can be stopped via the Central Administration. To stop (not remove) the Distributed Cache service by using Central Administration:
  • In Central Administration, click Application Management. In Service Applications
  • Click Manage Services on Server. On the Services on Server page, locate the Distributed Cache service. 
  • If the Distributed Cache service is started and you want to stop the service, under Action, click Stop.
Firewall configuration considerations
The Distributed Cache service uses the following communication ports:
  • 22233
  • 22234
  • 22235
  • 22236
How to Remove Distributed Cache Service:
To remove distributed Cache service from the server, use PowerShell. Going to Services on Server from SharePoint Central Administration site and clicking "Stop" next to distributed just stops the service but doesn't remove it from the cache cluster. You have to actually remove the service from the servers instead of stopping it to remove it! Use this PowerShell cmdlet:
Remove-SPDistributedCacheServiceInstance
Run this cmdlet on server(s) that doesn't need to run the Distributed Cache service. This simply removes the current server from cache host and Services on Server for the selected server! Removing the Distributed cache service instance and this will stop the app fabric caching service in service.msc, as well.

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


Tuesday, November 3, 2015

Create My Site for All Users in SharePoint using PowerShell

SharePoint My Sites are automatically created when the first time Users click on the My Content link. However, To promote the usage of SharePoint social, we deiced to pre-create SharePoint My sites for all users.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
Function Create-MySite($MySiteHost, $UserAccount) 
{
    #Get Objects
    $ServiceContext  = Get-SPServiceContext -site $MySiteHost
    $UserProfileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServiceContext)

    #Check if user Exists
    if ($UserProfileManager.UserExists($UserAccount)) 
    {
        #Get the User Profile
        $UserProfile = $UserProfileManager.GetUserProfile($UserAccount)
        
        #Check if User's My site is Cretaed already
        if($UserProfile.PersonalSite -eq $Null)
        {
            $UserProfile.CreatePersonalSite()
            write-host "My Site Created Successfully for the User!" -f Green
        }        
    }
    else
    {
        write-host "$($UserAccount) Not Found!" -f Red
    }
}

Create-MySite "https://mysite.crescent.com" "Crescent\Salaudeen"

SharePoint: Create Mysite for all users using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Variables
$MySiteHost = "https://mysite.crescent.com"
 
#Get Objects
$ServiceContext  = Get-SPServiceContext -site $MySiteHost
$UserProfileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServiceContext)

#Get All User Profiles
$UserProfiles = $UserProfileManager.GetEnumerator()

#Iterate through each profile
foreach ($Profile in $UserProfiles)
{
    if($Profile.PersonalSite -eq $Null)
    {
        #Check if User's My site is Cretaed already
        if($Profile.PersonalSite -eq $Null)
        {
            #$UserProfile.CreatePersonalSite()
            write-host "My Site Created Successfully for the User:" $Profile["AccountName"] -f Green
        }
        else
        {
            write-host "My Site Already Exists for the User:" $Profile["AccountName"] -f Red
        } 
    }
}
BTW, I've tested this script in SharePoint 2013 to create mysite for all users!


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


Sunday, November 1, 2015

Open Documents in Client Application Instead of Browser

Requirement: Enable Microsoft Word documents, Excel Spread sheets and PowerPoint Presentations to open in client applications like Microsoft Word, Excel and PowerPoint instead of opening them in browser directly.

Solution: 
In SharePoint 2013, you can enable open document in applications by configuring an option in document library settings.
  • Navigate to the Library >> Click on "Library Settings" from the Ribbon
  • Under General Settings, Click on "Advanced Settings" link
  • Under "Opening Documents in the Browser", choose "Open in the client application"
    sharepoint 2013 open document in application
  • Click "OK" to save your changes. 
Activate "Open Documents in Client Applications by Default" Feature:
While the above setting sets the document opening behavior at the specific document library, we've a built-in SharePoint 2013 feature called "Open Documents in Client Applications by Default" to control this behavior at site collection level. 

To Activate this feature:
  • Go to Site Settings >> Site Collection Features
  • Click on "Activate" button next to "Open Documents in Client Applications by Default" featuresharepoint 2013 open document in client application
Once you enable "Open Documents in Client Applications by Default" feature at site collection level, any new document library will follow the setting of "Open in the Client application". However for all existing document libraries in the site collection, this setting needs to be changed!

Definitely, you don't want to do it manually for each and every document library in the site collection, isn't it? Lets do PowerShell.

PowerShell script to change document open behavior:
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

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

#Get All sites under given site collection
$WebsColl = Get-SPSite $SiteURL -Limit All | Get-SPWeb -Limit All

#Iterate through each site
foreach($web in $WebsColl)
{
    #Get All document libraries 
    $LibrariesColl =$web.Lists | where {$_.BaseType -eq "DocumentLibrary" -and $_.BaseTemplate -eq "DocumentLibrary"}

    foreach($Library in $LibrariesColl)
    {
        #Set Document Open behavior
        $Library.DefaultItemOpen = "PreferClient"
        $Library.Update()
        Write-Host "Updated Document Library Settings on $($web.URL+"/"+$Library.RootFolder.URL)”
    }
}
This sets all documents in SharePoint 2013 to open document in client applications.

Related post: How to disable office web apps in SharePoint 2013

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


How to Make Attachments Mandatory in SharePoint List

Requirement: In a SharePoint list, make attachment required field!

Solution:
While, creating a Document library with metadata columns is one option, requirement is only to make the attachments mandatory in SharePoint list forms. To make attachment mandatory in SharePoint list we can use simple JavaScript. Add content editor or script editor web part on "NewForm.aspx" just below SharePoint list form web part, and then place the below code in it!

JavaScript to make attachments mandatory:
<script type="text/javascript" language="javascript">

function PreSaveAction() {
if (document.getElementById('idAttachmentsRow').style.display=='none' )
  {
     alert('Attachment is Mandatory! Please attach Documents.');
     return false ;
  }
else {  return true;  }
}
</script>

and here is the script in action:
sharepoint 2013 list attachment mandatory



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