Windows Server 2008 or Windows Server 2008 R2 includes a powerful utility named PowerShell Integrated Scripting Environment(ISE).It allows to debug PowerShell Scripts in a very efficient manner.But unfortunately it doesn’t give intellisense support.
SharePoint Foundation installs the PowerShell runtime ,but does not automatically install the PowerShell ISE. You have to explicitly enable it by adding a windows feature
Windows Server 2008 or Windows Server 2008 R2 includes a powerful utility named PowerShell Integrated Scripting Environment(ISE).It allows to debug PowerShell Scripts in a very efficient manner.But unfortunately it doesn’t give intellisense support.
SharePoint Foundation installs the PowerShell runtime ,but does not automatically install the PowerShell ISE. You have to explicitly enable it by adding a windows feature
PowerShell is based on reusable libraries containing functions known as cmdlets (pronounced command lets). Cmdlets have names which follow the convention of a common verb followed by a noun. For example, the built-in PowerShell libraries provide a cmdlet named Get-Process which returns a collection of objects representing the Windows processes running on the current machine.
PS D:\Users\Administrator> Get-Process
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
400 45 217700 223408 461 299.30 5172 Acrobat
80 10 1696 5188 72 0.03 5520 acrotray
66 9 1632 4712 68 0.03 1780 Adobelm_Cleanup.0001
66 9 1636 4672 68 0.03 6100 Adobelm_Cleanup.0001
54 7 1104 3060 28 0.00 5176 Adobelmsvc
41 4 1012 2508 15 0.00 1692 AESTSr64
48 6 2136 4972 54 0.73 1680 conhost
31 4 928 2392 22 0.00 4468 conhost
Pipelining in an important concept to understand when executing cmdlets. The basic idea is that every cmdlets returns an object or a collection of objects. Pipelining allows you to take the results of one cmdlets and pass it to a second cmdlet. The second cmdlets can run and then pass its results to a third cmdlets and so on. You create a pipeline by typing a sequence of cmdlets separated by the | (pipe) character.
cmdlet1 | cmdlet2 | cmdlet3
Example
if (dir | where {$_.length –gt 10kb}) {
“There were files longer than 10kb”
}
There are two common ways in which you can use PowerShell. First, you can execute commands interactively using the PowerShell console window. Second, you can write scripts to automate administration tasks.
Accessing PowerShell Console window
Start > All Programs > Accessories > Windows PowerShell > Windows PowerShell
Common Help
- Use the “exit” keyword to exit the shell
- Ctrl-C will interrupt the current task returning you to the prompt. A command can be spread over multiple lines and the interpreter will prompt for additional input. The line continuation character is the back-quote ‘`’ (also called the back-tick).
- Ctrl-C will interrupt the current task returning you to the prompt.
- To get help about a command you can do “help command”. The help command by itself will give you a list of topics.
- The help command supports wildcards so “help get-*” will return all of the commands that start with “get-”.
- You can also get basic help on a command by doing “commandName -?” like “dir –?”
Variables in Power Shell
PS > $x= 5
PS > echo $x
5
PS >
Arrays
PS > $x= Subhasis,Daniel, Mac
PS > echo $x[1]
Daniel
PS >
HashTable
PS > $h= @{a=1;b=2;c=3}
PS > echo $h
Name Value
a 1
b 2
c 3
Flow-control Statements:
These Statements can be used to iterate the user collections
if Statement:
if ($b –eq 15) { $a=13} else {$a=15}
The condition part of an if statement may also be a pipeline.
if (dir | where {$_.length –gt 10kb})
{
“There were files longer than 10kb”
}
while Loop:
$b=1; while ($b –lt 10) { echo $b }
for Loop:
for ($i=0; $i –lt 10; $i++)
{
echo $i
}
foreach Loop:
foreach ($i in 1..10)
{
$echo $i
}
Why PowerShell ? Why Now ?
PowerShell was designed to do for Windows what the UNIX shells do for UNIX: provide a powerful, well-integrated command-line experience for the operation
system. Unfortunately since Windows is mostly managed through objects (WMI, COM and .NET) this required creating a new kind
of shell. So why create it now? As Windows moves off the desktop
and into server farms or application servers like print, DNS
and LDAP services, command-line automation becomes a
fundamental requirement.
PowerShell is freely available through the Microsoft Windows Update Service packaged as an optional update for Windows XP SP2, Windows Vista and Windows Server 2003. It is also included with Windows Server 2008 as an optional component.
In Sharepoint 2007,Farm Administrators used STSADM.EXE to do the administrative tasks. SharePoint Foundation still installs STSADM.EXE but it is primarily included to support backwards compatibility with scripts migrating from earlier versions.
PowerShell is something i was always love to have in the production farm.In MOSS 2007,there were many things which can be done through object model easily,can’t done through STSADM.EXE.Sharepoint 2010 is the first version to directly support PowerShell.In PowerShell, You can directly access Sharepoint object model through the codes in the console window. Nice …isn’t it ?
I started exploring PowerShell long back. In next couple of posts, i will try to provide comprehensive list of operations you need to know to get your hands dirty on PowerShell.
http://msdn.microsoft.com/en-us/library/ee554869(office.14).aspx
Only thing missing is installing Visual studio 2010. Install visual studio 2010 first and then proceed towards installation of sharepoint 2010.
http://andreasglaser.net/post/2009/11/17/Installing-SharePoint-Server-2010-on-Windows-Server-2008-R2-and-SQL-Server-2008-R2-Part-1-Overview.aspx
There will be two errors most likely to come while configuration wizard is running.
Failed to register SharePoint services.
An exception of type System.TypeLoadException was thrown. Additional exception information: Could not load type 'Microsoft.Office.Server.Search.Administration.SearchWebServiceManagerService' from assembly 'Microsoft.Office.Server.Search, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C'.
System.TypeLoadException: Could not load type 'Microsoft.Office.Server.Search.Administration.SearchWebServiceManagerService' from assembly 'Microsoft.Office.Server.Search, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C'.
at System.RuntimeTypeHandle._GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, Boolean loadTypeFromPartialName)
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.RuntimeType.PrivateGetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase)
at Microsoft.SharePoint.PostSetupConfiguration.ReflectionHelper.InvokeConstructor(String assemblyQualifiedName, Type[] constructorSignature, Object[] constructorParameters)
at Microsoft.SharePoint.PostSetupConfiguration.TaskCommon.ReflectionHelperInvokeConstructor(String assemblyQualifiedName, Type[] constructorSignature, Object[] constructorParameters, TaskBase task)
at Microsoft.SharePoint.PostSetupConfiguration.ServicesTask.InvokeServiceConstructor(String serviceRegistryKeyName, String solutionIdRegistryName, String serviceNameRegistryName, Type[] constructorSignature, Object[] constructorParameters)
at Microsoft.SharePoint.PostSetupConfiguration.ServicesTask.InstallServiceInConfigDB(Boolean provisionTheServiceToo, String serviceRegistryKeyName)
at Microsoft.SharePoint.PostSetupConfiguration.ServicesTask.InstallServices(Boolean provisionTheServicesToo)
at Microsoft.SharePoint.PostSetupConfiguration.ServicesTask.Run()
at Microsoft.SharePoint.PostSetupConfiguration.TaskThread.ExecuteTask()
----------------------------------------------------------------------------------------------------------------------------------------------
This error can be removed by removing the following registry keys
Removing the following registry keys fixed the problem:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0\WSS\Services\Microsoft.Office.Server.Search.Administration.SearchWebServiceManagerService]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0\WSS\ServiceProxies\Microsoft.Office.Server.Search.Administration.SearchWebServiceManagerServiceProxy]
2. Error in step 8
Failed to create sample data.
An exception of type Microsoft.Office.Server.UserProfiles.UserProfileException was thrown. Additional exception information: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (application/soap+msbin1). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: ....
This error can be removed by installing the following hotfix
http://go.microsoft.com/fwlink/?LinkID=166231
In Sharepoint point sites, if are storing data in a sharepoint list, then you can use inbuilt “Custom list” webpart to display data in the sharepoint pages .But, What if the Data is stored other than sharepoint lists and you want to display the data in sharepoint list style ? In my scenario, I have the requirement that, I have to show data from sql server database in sharepoint list style .Here is something I found interesting.
Sharepoint uses Microsoft.SharePoint.WebControls.SPGridView control to display its own list. Here goes the webpart
It contains almost everything; you can do with a SPGridView.To start with let’s add a GridView to the Webpart and assign data source
using System;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Drawing;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
#region Method : CreateChildControls
///
/// Method Name : CreateChildControls
/// Description : Method for creating the child controls.
///
protected override void CreateChildControls()
{
//Defining the grid view
SPGridView customGridView = new SPGridView();
//Here GetCustomData() function returns a dataset.
customGridView.DataSource = GetCustomData();
this.Controls.Add(customGridView);
}
In this case, the columns are auto generated based on the data columns in the dataset.
Let’s include List items menu’s to the individual row of the grid view. Let’s include the following code for service grid view inside create child controls.
serviceGridView.AutoGenerateColumns = false;
SPBoundField titleBoundField = new SPBoundField();
//Assigning the Columnname which is coming from the dataset
titleBoundField.DataField = “TITLE”;
titleBoundField.HeaderText = " Service Title";
titleBoundField.HeaderStyle.CssClas=ConstantVariables.GetMSFormBobyCSS;
SPBoundField serviceIDBoundField = new SPBoundField();
serviceIDBoundField.DataField = SERVICEID;
serviceIDBoundField.HeaderText = "ServiceID";
serviceIDBoundField.Visible = false;
serviceIDBoundField.HeaderStyle.CssClass= “myCustomClass”; customGridView.Columns.Add(titleBoundField);
customGridView.Columns.Add(serviceIDBoundField);
titleBoundField.Visible = false;
//Defining Menu Field for the Title
titleMenuField = new SPMenuField();
titleMenuField.HeaderText = "Service Title";
titleMenuField.TextFields = TITLE;
titleMenuField.HeaderStyle.CssClass = “myCustomClass”;
titleMenuField.MenuTemplateId = "ServicesMenu";
titleMenuField.TokenNameAndValueFields = "CustomID=ServiceID";
titleMenuField.SortExpression = TITLE;
MenuTemplate servicesListMenuTemplate = new MenuTemplate();
servicesListMenuTemplate.ID = "ServicesMenu";
//Defining Menu Templates for the menu
MenuItemTemplate viewMenuItemTemplate = new MenuItemTemplate("View Details");
StringBuilder viewDetailsUrl = new StringBuilder();
viewDetailsUrl.Append(“http://google.com”);
//Adding event on menu item click
viewMenuItemTemplate.ClientOnClickNavigateUrl=viewDetailsUrl.ToString();
servicesListMenuTemplate.Controls.Add(viewMenuItemTemplate);
MenuItemTemplate editMenuItemTemplate = new MenuItemTemplate("Edit Details");
StringBuilder editDetailsUrl = new StringBuilder();
editDetailsUrl.Append(“http://www.msdn.com”);
//Adding event on menu item click
editMenuItemTemplate.ClientOnClickNavigateUrl=editDetailsUrl.ToString();
servicesListMenuTemplate.Controls.Add(editMenuItemTemplate);
deleteMenuItemTemplate = new MenuItemTemplate("Delete");
deleteMenuItemTemplate.ClientOnClickScript = "javascript:do_confirmService('" + this.UniqueID + "','%CustomID%');";
servicesListMenuTemplate.Controls.Add(deleteMenuItemTemplate);
//Adding seperator template
MenuSeparatorTemplate sepMenuTemplate = new MenuSeparatorTemplate();
servicesListMenuTemplate.Controls.Add(sepMenuTemplate);
this.Controls.Add(servicesListMenuTemplate);
customGridView.Columns.Add(titleMenuField);
//Defining Description Column
SPBoundField statusBoundField = new SPBoundField();
statusBoundField.DataField = "Status";
statusBoundField.HeaderText = "Status";
statusBoundField.HeaderStyle.CssClass = ConstantVariables.GetMSFormBobyCSS;
customGridView.Columns.Add(statusBoundField);
SPBoundField languageBoundField = new SPBoundField();
languageBoundField.DataField = " Language ";
languageBoundField.HeaderText = "Language";
languageBoundField.HeaderStyle.CssClass = ConstantVariables.GetMSFormBobyCSS;
customGridView.Columns.Add(languageBoundField);
The most important thing above are the click event of each menu item.
1. If you want to redirect to some URL on menu item click, then you can use ClientOnClickNavigateUrl property of MenuItemTemplate
This is done here for “View Details” and “Edit Details” menu Item.
Eg : viewMenuItemTemplate.ClientOnClickNavigateUrl=viewDetailsUrl.ToString();
Here Clicking View Detail page will redirect to http://www.google.com/.
On Click of “Edit Detail” page will redirect to “http://www.msdn.com
2. What if you want some server side functionality on the client click.
You need to do four things over here.
2.1. Implement IPostBackEventHandler. Your class goes like this
using System.Web.UI;
public class Services : Microsoft.SharePoint.WebPartPages.WebPart, IPostBackEventHandler
{
}
2.2. Register your javascript file OnPreRender() method.
2.3. Call the javascript method on ClientOnClickScript event of MenuItemTemplate
Eg :
deleteMenuItemTemplate.ClientOnClickScript = "javascript:do_confirmService('" + this.UniqueID + "','% CustomID %');";
Here ‘%Name%’ is assigned to the datafield defined the Token
TokenNameAndValueFields of the MenuField
Eg : titleMenuField.TokenNameAndValueFields = " CustomID=ServiceID";
Here DataSet has a column ServiceID. So on click of delete Menu item of a particular row, serviceID of that row is passed as a parameter to the javascript.
The Javascript File goes here
File : CustomJavaScript.js
-----------------------------------------------------------------------
function do_confirmService(ID,Name)
{
if (confirm('Are you sure you want to delete the service?'))
{__doPostBack(ID,Name)
}
;
-----------------------------------------------------------------------
On click of “delete” menu item it will ask for the conformation .If you click ok, then it will do a PostBack.
2.4. Implement RaisePostBackEvent as part of IPostBackEventHandler Interface
#region Event : RaisePostBackEvent
///
/// Method Name : RaisePostBackEvent
/// Description : This method is the implementation of IPostBackEventHandler Interface and is used to Delete A Service Record while Postback event.
///
/// string
public void RaisePostBackEvent(string eventArgument)
{
//Check for the ServiceID which is passed as parameter
//here in eventArgument gives the ServiceID which is passed to javascript
}
#endregion
Enabling Paging in SPGridview
Add the follwing lines
customGridView.AllowPaging = true;
customGridView.PageSize = 15;
customGridView.PagerSettings.Mode = PagerButtons.NumericFirstLast;
serviceGridView.PageIndexChanging += new GridViewPageEventHandler(customGridView _PageIndexChanging);
//Creating Event Handler for Page index changing
#region Event : customGridView _PageIndexChanging
//
/// Method Name : serviceGridView_PageIndexChanging
/// Description : This method handles Page Indexing Event of gridview
///
/// GridViewPageEventArgs
/// object
private void customGridView _PageIndexChanging(object sender, GridViewPageEventArgs e)
{
customGridView.PageIndex = e.NewPageIndex;
customGridView.DataBind();
}
#endregion
Add following lines after adding SPGridview to the control collection.
Eg : this.Controls.Add(customGridView);
customGridView.PagerTemplate = null;
customGridView.DataBind();
Don’t DataBind the gridview before adding the control to the control collection in case of paging.
Enabling Grouping in SPGridview
customGridView.AllowGrouping = true; customGridView.AllowGroupCollapse = true; customGridView.GroupField = "TITLE"; customGridView.GroupDescriptionField = "TITLE"; customGridView.GroupFieldDisplayName = "TITLE ";