Add Column to List and Content type Using Powershell

Below is the code you need to execute to add a column to List and Content type using PowerShell. Copy below code to notepad, rename the notepad with CreateField.ps1 and then execute the code from PowerShell.

PowerShell

#####################Code Starts

# Add PsSnapin if not already added

if ( (Get-PSSnapin -Name Microsoft.Sharepoint.Powershell -ErrorAction SilentlyContinue) -eq $null )

{

Add-PsSnapin Microsoft.Sharepoint.Powershell

}

# Call the function with WebURL, List Name – where you want to add column

# FieldName – the nae of the filed you want to add – type is hardcoded in below function

# Contenttype name – the content type name you want to add field to

function CreateColumn($webUrl, $listName, $fieldName, $contentTypeName )

{ $web = Get-SPWeb $webUrl

Write-Host “$($web.URL)”

$pageList = $web.Lists[$listName]

Write-Host “$($pageList.URL)”

$pageFieldisNewTillDate = $pageList.Fields.Add($fieldName, “DateTime”, 0)

$pageList.Fields[$pageFieldisNewTillDate].Title = $fieldName

$pageList.Fields[$pageFieldisNewTillDate].Description = “Description here”

$pageList.Fields[$pageFieldisNewTillDate].DisplayFormat = “DateOnly”

$pageList.Fields[$pageFieldisNewTillDate].Update()

$pageList.Update();

$field = $pageList.Fields[$fieldName]

Write-Host “Field created” + “$($field)”

$fieldlink = New-Object Microsoft.SharePoint.SPFieldLink $field

#Write-Host “$($fieldlink)”

$contentTypeContact = $pageList.ContentTypes[$contentTypeName]

Write-Host “$($contentTypeContact.Title)”

#add the new field to content type you need

$contentTypeContact.FieldLinks.Add($fieldlink)

$contentTypeContact.Update()

$web.Dispose();

}

# Function is called with valied input parameters

CreateColumn -webUrl “https://xxx.com/Contacts” -listName “Pages” -fieldName “isValidTillDate” -contentTypeName “Contacts”

CreateColumn -webUrl “https://xxx.com/KnowledgeUpdate” -listName “Pages” -fieldName “isValidTillDate” -contentTypeName “KnowledgeUpdate”

#####################Code Ends

Feel free to drop me email on bipinparshottam@gmail.com, skype:bipin.pankhania incase of queries.

Advertisements

Percentage Complete Progress Bar in SharePoint 2013

% Complete Progress bar in SharePoint 2013

Need to add following Javascript code to MasterPage Gallary. Here we have added tasklist.js file, need to select below content type and other properties.AddMaster

Copy paste below code between start and end to text file, rename it with TaskList.Js

Code:

/*****************Starts************************/

codeFunction

//Please drop me an email if you want code, as I am unable to copy paste in my blog, hence I have given the screenshot of the code.

/******************Ends*******************/

Need to Add TaskList -> List View webpart to specific page, Edit webpart, under Miscellaneous properties of webpart, provide the path of the TaskList.Js file from where it needs to pick up latest JavaScript code.

WebpartProperties

After this click on OK , Save and Check in the page. This will show task list %complete as follows.

ProgressBar

The main code in TaskList.Js is below, this code arranges nested div and span in proper style, with modification in Span, one can choose to display % Left or right aligned.

Below is the main code from JavaScript function

code

————————————–

for queries, suggestions, feedback contact me on

email :bipinparshottam@gmail.com

skype: bipin.pankhania

Create Host named site collection

Create Host named site collection using PowerShell
Need to execute below Script to Create Host named site collection using PowerShell.

Add-PSSnapin Microsoft.Sharepoint.Powershell

New-SPSitehttp://siteurl’ -HostHeaderWebApplication ‘http://webapplicationurl’ -Name ‘TitleYouwanttoCreate’ -Description ‘Site description’ -OwnerAlias ‘admin’ -language 1033 -Template ‘BLANKINTERNET#0’

Above fields are self-explanatory, need to supply
SPSite -> SiteCollection URL -> the way you want to create it for SPSite
HostHeaderWebApplication -> Webapplication URL on top of which you need to create Site Collection.
Name – Site Collection name
Description – Site Collection description
OwnerAlias – System Admin account
Language -1033 for UK English
Template – the template code you need to create Site Collection.

————————————–

for queries, suggestions, feedback contact me on

email :bipinparshottam@gmail.com

skype: bipin.pankhania

Get all workflows associated with all lists in Site

Here I have written a PowerShell script to find details of all workflows associated with all lists in Site Collection.

//Script Starts

Add-PSSnapin Microsoft.Sharepoint.Powershell
$url = “http://contoso.com”

$spSite = new-object Microsoft.SharePoint.SPSite($url)
foreach($web in $spSite.AllWebs)
{
foreach($list in $web.Lists)
{
foreach($wf in $list.WorkflowAssociations)
{
Write-Host “$($list.Title)” -foreground White
 Write-Host “$($wf.Name)” -foreground Green
}
}

}
$spSite.Dispose()

//Script ends

This script provides details on workflow associated with list, once we get the information about workflow, we can execute other commands as required.

————————————–

for queries, suggestions, feedback contact me on

email :bipinparshottam@gmail.com

skype: bipin.pankhania

Custom Content Query Webpart View Additional/Custom Fields

Here I would like to explain details on How to fetch additional/custom fields in Custom Content Query webpart programmatically.

We can set CommonViewFields property of Custom Content Query webpart to fetch additional/Custom column.

Following is the example of sample Custom Content Query Webpart, I assume user has basic knowledge on how to create Custom Content Query webpart class. It is a normal class which Inherits from ContentByQueryWebPart

public class CustomCQWP : ContentByQueryWebPart
{

//Variable Declaration(same approach we take generally for class)

public string srtTBD;

Public int intTBD; etc.

// Override onInit method

protected override void OnInit(EventArgs e)
{

//here we write our sample query which will override existing ContentQueryWebPart’s Query.

base.OnInit(e);
SPQuery query = new SPQuery();

QueryOverride = “<Query><Where><Eq><FieldRef Name=\”Title\” /><Value        Type=\”Text\”>test</Value></Eq></Where></Query>”;

//here we specify additional/custom field which query should bring across

// this is similar to adding one more field to viewFields in CAML Query

QueryOverride = query.Query;
this.CommonViewFields = “PublishingPageContent,Publishing HTML”;

//this.CommonViewFields syntax would be “Internal Name, DataType”

}

protected override void CreateChildControls()

{ // Your code here..

}

}

————————————–

for queries, suggestions, feedback contact me on

email :bipinparshottam@gmail.com

skype: bipin.pankhania

Write to ULS Logs Programmatically in SharePoint 2013/SharePoint 2010 On Premise

This is in continuation with blog I posted on “ULS logs in SharePoint 2013/SharePoint 2010 on premise

Here I would provide approach to write to ULS logs programmatically. User needs to have basic knowledge on how to open Visual Studio 2010/2012/2013 and should have basic knowledge on how to write a class.

To start with we will create a class in Visual Studio, need to paste following code to class(please make formatting changes).

//Class Starts

———————————————————————————————-

using System.Collections.Generic;
using Microsoft.SharePoint.Administration;

namespace SampleLogger.ULSLog
{
public class SampleLogger : SPDiagnosticsServiceBase
{
private const string PName= “Sample Log “;

private static SampleLogger  logger;

 private SampleLogger() : base(PRODUCTNAME + “ULS Logging Service”,            SPFarm.Local)
{}

/// <summary>
/// Here we create Log Instance
/// </summary>
private static SampleLogger loggerInstance
{
get
{
if ( samplelogger != null) return samplelogger;
else return samplelogger = new SampleLogger();
}
}

/// <summary>
/// Options to specify different Log Category under which logs will be    classified in ULS log
/// </summary>
/// <returns></returns>
protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
{
var diagnosticsCategories = new List<SPDiagnosticsCategory>
{

//One can add more categories as per requirement
new SPDiagnosticsCategory(LogCategory.ApplicationPages.ToString(),               TraceSeverity.Unexpected, EventSeverity.Error),
new SPDiagnosticsCategory(“SampleLogger Details”,                                                 TraceSeverity.Monitorable, EventSeverity.Information)
};
var areas = new List<SPDiagnosticsArea>
{
new SPDiagnosticsArea(PName, diagnosticsCategories)
};

return areas;
}

/// <summary>
/// Follwoing creates Trace Entry
/// </summary>
/// <param name=”methodName”>Method Name Object</param>
/// <param name=”traceMessage”>Log Message</param>
 public static void WritetoULS(string methodName, string traceMessage)
{
SPDiagnosticsCategory category =                                                                                    loggerInstance.Areas[PName].Categories[“SampleLogger Details”];
loggerInstance.WriteTrace(0, category, TraceSeverity.Monitorable, PName+ ” Custom::” + methodName + “::” + traceMessage);
}
}
}

———————————————————————————————-

//Class ends

Now Call the class from other location(webpart.cs, usercontrol.cs, event receivers, other class.cs) etc to use and write to ULS logs

SampleLogger.ULSLog.WritetoULS(“Your Sample details here”, “Anyother info you feel needs to be written”);

————————————–

for queries, suggestions, feedback contact me on

email :bipinparshottam@gmail.com

skype: bipin.pankhania

ULS logs in SharePoint 2013/SharePoint 2010 on premise

ULS (Trace) Logs in SharePoint 2013/SharePoint 2010 on premise

Here I would explain details on how to write to ULS logs using code behind (this will be covered in next post), also I would focus on how to change ULS logs file path. This all implies for SharePoint on premise and not for SharePoint Online.

First let’s start with where ULS logs are stored by default on server and how to change the default path.

Following are details for SharePoint 2010

To find ULS logs path on server, need to go to

Central Admin -> Monitoring -> Configure Diagnostic Logging under Reporting

configureULS

Click on Configure Diagnostic Logging will take us to Log Details page from where we can check path for ULS(Trace) logs.

ULSPath

Default path is (14 Hive): C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS

From here we can change path if we wish to store ULS logs to different location else it will be stored at above location on server.

Similar Details we have for SharePoint 2013, there is no change but for your reference I would add Screenshots here.

To find ULS logs path on server, need to go to

Central Admin -> Monitoring -> Configure Diagnostic Logging under Reporting(Same as SharePoint 2010).

SP2013

Click on Configure Diagnostic Logging will take us to Log Details page from where we can check path for ULS(Trace) logs.

Here I have changed default path(15 Hive) to point to other path on server.

SP2013Path

Other details can be configured are

  • Number of days to store logs files
  • Restrict Trace log

This includes details on how to view ULS log files from server and also how to modify default location for ULS logs, next article would focus on how to write custom message to ULS logs.

————————————–

for queries, suggestions, feedback contact me on

email :bipinparshottam@gmail.com

skype: bipin.pankhania