Thursday, December 29, 2011

BackUp and Restore sites using PowerShell

Site Collection:

Backup-SPSite http://server_name/sites/site_name -Path C:\Backup\site_name.bak

Restore-SPSite http://server_name/sites/site_name -Path C:\Backup\site_name.bak -Force

Site:

Export-SPWeb http://site –Path C:\site_name.cmp

Import-SPWeb http://site –Path C:\site_name.cmp –UpdateVersions -Overwrite

Wednesday, December 21, 2011

Change the 'Add new' link in document library

  • First find the ID of the <a> tag.. then
  • Add the following code to the current page either using SharePoint designer or by adding a Content query webpart
       <script>
         document.getElementById("<id of the control>").innerHTML="Sample Text"
       </script>

Progress Bar for Tasks List in SharePoint 2010


Progress Bar for Tasks List in SharePoint 2010

Now we are going to see how to show the progress of tasks in SharePoint

We are going achieve this with the help of Calculated Columns.







The [% Complete] is a default column in tasks lists. We just need to add – in a calculated column - the formulas for this specific use case. Here they are:


Progress Bar 1 :


=”<DIV style=’background-color:blue; width:”&([% Complete]*100)&”%;’>&nbsp;</DIV>”


Progress Bar 2 :


=”<DIV style=’background-color:red;’><DIV style=’background-color:LimeGreen; width:”&([% Complete]*100)&”%;’>&nbsp;</DIV></DIV>”


Progress Bar 3:



="<DIV style=’position:relative;padding-top:2px;
border:1px solid Gainsboro; background-color: "
&CHOOSE(RIGHT(LEFT(Priority,2),1), "LightSalmon", "LemonChiffon", "Chartreuse")&";’>
<DIV style=’margin:0;padding:0;font-size:0px;border-top:12px solid "
&CHOOSE(RIGHT(LEFT(Priority,2),1),"Crimson","orange","green")&"; width:"
&IF(Status="Not Started","1%",
IF(Status="Completed","100%",TEXT([% Complete],"0%")))&";’></DIV>
<DIV style=’position:absolute; top:2px;left:2px;’>"
&IF(Status="Not Started","0%",IF(Status="Completed","100%",TEXT([% Complete],"0%")))&"
</DIV></DIV>"

Note: the &nbsp; character is mandatory to make this work in Firefox.

Once you have done this, your tasks list looks like this













To achieve our expected result, we have to do one more thing

Add a HTML Form Web Part and enter the below script

Script:


<script type="text/javascript">
if(typeof jQuery=="undefined"){
var jQPath="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/";
document.write("<script src='",jQPath,"jquery.min.js' type='text/javascript'><\/script>");
}
</script>




<script type="text/javascript">




$(document).ready(function(){
$(".ms-vb2:contains('<DIV')").each(function(){
var tempDIV = document.createElement ("DIV");
tempDIV.style.cursor = "pointer";
tempDIV.innerHTML = $(this).text();
$(this).text("");
$(this).append(tempDIV);




});
});
</script>


Now your SharePoint List look like






Cool...........


It works now,  you can do many more things using jQuery and Calculated column.


If you are looking for other colors, here is a very good reference:
http://www.w3schools.com/html/html_colornames.asp



do let us know your experience with this post.
Cheers, 

Monday, December 19, 2011

Data Connection Exceeded Maximum Limit Error in InfoPath 2010 Browser Form

  • Open the SharePoint 2010 Central Administration,
  • Go to General Application Settings => Configure InfoPath forms services
  • Change the Data connection response size.

Error : Exceeds the list view threshold


  • Open the SharePoint 2010 Central Administration,
  • Go to Application Management => Manage Web Applications
  • Then select your web application
  • In the Ribbon, select the General Settings => Resource Throttling
  • There you can see the threshold limit 5000, edit the value as you need and save it.

Tuesday, November 29, 2011

Unable to process the request (While opening an Excel document)

On opening the excel document stored in a document library it shows 'Unable to process the request. Wait a few miniutes and try performing this operation again.

To solve this, edit the 'serverfilesExcelServer.xml' available in the SharePoint 14 hive.

'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML'

Comment the lines containing the file extension of xlsx or xls.

<?xml version=”1.0″ encoding=”utf-8″ ?>
<!– Copyright (c) Microsoft Corporation. All rights reserved. –>
<ServerFiles>
     <!–<Mapping FileExtension=”xlsx” RedirectUrlTemplate=”/_layouts/xlviewer.aspx?id=|0″ NoGetRedirect=”TRUE” CreateRedirectUrlTemplate=”/_layouts/xlviewer.aspx?new=1″/> –>
     <Mapping FileExtension=”xlsb” RedirectUrlTemplate=”/_layouts/xlviewer.aspx?id=|0″ NoGetRedirect=”TRUE” CreateRedirectUrlTemplate=”/_layouts/xlviewer.aspx?new=1″/>
     <Mapping FileExtension=”xlsm” RedirectUrlTemplate=”/_layouts/xlviewer.aspx?id=|0″ NoGetRedirect=”TRUE” CreateRedirectUrlTemplate=”/_layouts/xlviewer.aspx?new=1″/>
 </ServerFiles>


Then perform an IISRESET which solves the problem.

Wednesday, November 16, 2011

SharePoint Developer Interview Questions – Answers

Adding Notification and Status in SharePoint through Client Object Model

<script language="ecmascript" type="text/ecmascript">
var statusId = '';
var notifyId = '';
function AddNotification() {
    notifyId = SP.UI.Notify.addNotification("Hello World!", true);
}
function RemoveNotification() {
    SP.UI.Notify.removeNotification(notifyId);
    notifyId  = '';
}
function AddStatus() {
    statusId = SP.UI.Status.addStatus("Status good!");
    SP.UI.Status.setStatusPriColor(statusId, 'red');
}
function RemoveLastStatus() {
    SP.UI.Status.removeStatus(statusId);
    statusId = '';
}
function RemoveAllStatus() {
    SP.UI.Status.removeAllStatus(true);
}
</script>
<input id="Button1" onclick="AddNotification()" type="button" value="Add Notification"/>
<input id="Button2" onclick="RemoveNotification()" type="button" value="Remove Notification"/>
<input id="Button3" onclick="AddStatus()" type="button" value="Add Status"/>
<input id="Button4" onclick="RemoveLastStatus()" type="button" value="Remove Last Status"/>
<input id="Button5" onclick="RemoveAllStatus()" type="button" value="Remove All Status"/>

Thursday, October 20, 2011

Sending mail with image in PowerShell

$smtpServer = "<smtp server name>"
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment("<image path>")
$att.ContentDisposition.Inline = $True
$att.ContentDisposition.DispositionType = "Inline"
$att.ContentType.MediaType = "image/jpeg"
$att.ContentId = "logo"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.IsBodyHTML = $True
$msg.From = "<from address>"
$msg.To.Add("<to address>")
$msg.cc.Add("<cc address>")
$msg.Subject = "<mail subject>"
$msg.Attachments.Add($att)
$msg.Body = "<mail body>... <img src='cid:logo'>"
Add-Content -Path "d:\mylog.txt" -Value "Mail Sent..."
$smtp.Send($msg)
$att.Dispose()

Sending mail with attachment in PowerShell

$file = "c:\myfile.text"
$smtpServer = "<smtpservername>"
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($file)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "<from address>"
$msg.To.Add("<to address>")
$msg.Subject = "<mail subject>"
$msg.Body = "<mail body>"
$msg.Attachments.Add($att)
$smtp.Send($msg)
$att.Dispose()

Wednesday, October 12, 2011

PowerShell script to send mail

        $headers = New-Object System.Collections.Specialized.StringDictionary
        $headers.Add("to", "test1@abc.com")
        $headers.Add("cc", "test2@abc.com")
        $headers.Add("bcc", "test3@abc.com")
        $headers.Add("from", "test@test.com")
        $headers.Add("subject", "Test Email Subject")
        $headers.Add("content-type", "text/html")
        $bodyText = "Hello how are you?"
        [Microsoft.SharePoint.Utilities.SPUtility]::SendEmail($web, $headers, $bodyText)

Friday, October 7, 2011

In Infopath the Conditions in rules are limited to only 5 !!!

You can overcome this by changing your last condition to "The expression" and use "and" or "or" as needed to create your compound condition. So, for example, if you need to make sure both field1 and field2 are not blank, you'd use the expression:



If you need help figuring out the correct syntax for your expression, first set up the condition using the drop downs (for example, select field1 in your first drop down, then "is not blank" in your second drop down), then change the first drop down to "The expression" -- whatever your condition was will auto populate into the box for the expression. Paste that into a text editor, and then do the same for the rest of your conditions. Add and or or between them as needed, and you have your expression!

Thursday, October 6, 2011

How to check the SharePoint Installation Type (Standalone/farm

Here we can easily find out the type of SharePoint Installation on your machine.

1. Open Registry editer
Run>regedit.exe

2. Navigate this path
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0\WSS

check the "ServerRole"


There will be an entry for "ServerRole" which type of your installation
SINGLESERVER - Stand Alone
APPLICATION - Farm Complete
WFE - Web Front End

Wednesday, September 21, 2011

Auto Refreshing Parent Page after close the SP Modal PopUp

Hi,This is my first post....

function createitem(obj) {
var options = {
width: 700,
height: 400,
url:obj,
title: "Create Item",
};
//For Auto Refreshing Parent Page
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
//Open Pop Up
SP.UI.ModalDialog.showModalDialog(options);

//Parent Page Refresh
function CloseCallback(result, target) {

window.location.reload()

}

return false;
}


Hope it 'll be make your work easy......

Hi

This is Ariff SharePoint 2010 Administrator

Change SharePoint 2010 Central Administration port number:


How to change SharePoint 2010 Central Administration port number:


Use: Set-SPCentralAdministration (if using an allowed port)
Set-SpCentralAdministration -port 1024 iisreset #And use whatever port number you choose #Note: the above command will make changes to IIS as well
If your port is between 1023 and 32767 (and is not port 443), then that should do it for you. But if you are trying a port outside that range, continue reading...

Use: stsadm -o setadminport (if using a "blocked" port)

If you choose a port number outside the range of 1023 - 32767, you may get error. For example, I triedSet-SpCentralAdministration with port 81 and got an Invalid Port error.
Set-SPCentralAdministration : The pipeline has been stopped. At line:1 char:28 + set-spcentraladministration ====  -port 81     + CategoryInfo          : InvalidData: (Microsoft.Share...lAdministration:SPCmdletSetSPCentralAdministration) [Set    -SPCentralAdministration], PipelineStoppedException     + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletSetSPCentralAdministration   Set-SPCentralAdministration : Invalid Port At line:1 char:28 + set-spcentraladministration ==== -port 81     + CategoryInfo          : InvalidArgument: (81:Int32) [Set-SPCentralAdministration], InvalidOperationException     + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletSetSPCentralAdministration
The reason: Set-SpCentralAdministration blocks the following ports:
  • Lower than 1023
  • Higher than 32767
  • 443 (SSL)
Obviously, our chosen port 81 is below 1023, which explains it. I tried other port numbers and they did work. But I didn't want -those- port numbers... I wanted port 81. So... "if you have a port number you are trying to use and there's nobody else who can fix it..." Technet advises using:
stsadm -o setadminport -port 81 iisreset

Use: New-SpCentralAdministration (if using a "blocked" port and you skipped the section above this)

Before I found the Technet article above, I tried "New-SpCentralAdministration -port 81" just to see what would happen. Let me be clear: I'm not completely sure what happened when I ran this command. Evidently, whatever I expected to happen when I ran "Set-SpCentralAdministration" happened when I ran "New-SpCentralAdministration": It re-assigned the Central Administration port number and got rid of my old Central Administration site at the previous port. If you run this command, look under "Alternate Access Mappings." You'll see that it has created a 2nd Internal URL:
Internal URLZonePublic URL for Zone
http://servername1:448Defaulthttp://servername1:81*
http://servername1:81Defaulthttp://servername1:81
*The URL with the 81 port number is the one created with New-SpCentralAdministration. I deleted the first row (the 448 row).


Saturday, September 17, 2011

Wednesday, August 17, 2011

Grant folder permission(SharePoint) using powershell script

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
 $site = new-object Microsoft.SharePoint.SPSite("http://myserver/")
 $web = $site.OpenWeb()
 function GrantGroupPermission($groupName)
 {
  [Microsoft.SharePoint.SPGroupCollection]$spgroups = $web.SiteGroups
  [Microsoft.SharePoint.SPGroup]$spgroup = $groups[$groupName]
  $sproleass=new-object Microsoft.SharePoint.SPRoleAssignment([Microsoft.SharePoint.SPPrincipal]$spgroup)
  $folder.BreakRoleInheritance("true")
  $sproleass.RoleDefinitionBindings.Add($web.RoleDefinitions["Contribute"])
  $folder.RoleAssignments.Add($sproleass);
  Write-Host "Permission provided for group ", $groupName
 }
 function GrantUserpermission($userName)
 {
  [Microsoft.SharePoint.SPUserCollection]$spusers=[Microsoft.SharePoint.SPUserCollection]$web.SiteUsers
  [Microsoft.SharePoint.SPUser]$spuser=$spusers[$userName]
  $sproleass=new-object Microsoft.SharePoint.SPRoleAssignment([Microsoft.SharePoint.SPPrincipal]$spuser)
  $folder.BreakRoleInheritance("true")
  $sproleass.RoleDefinitionBindings.Add($web.RoleDefinitions["Contribute"])
  $folder.RoleAssignments.Add($sproleass);
  Write-Host "Permission provided for user ", $userName
 }
 $doclib=[Microsoft.SharePoint.SPDocumentLibrary]$web.Lists["Shared Documents"]
 $foldercoll=$doclib.Folders;
 foreach($folder in $foldercoll)
 {
  Write-Host $folder.Name
  if($folder.Name.Equals("f2"))
  {
   GrantUserPermission("raj")
  }
 
 }
 Write-Host "Completed...."
 $web.Close()
 $site.Dispose()

Friday, May 20, 2011

Basic STSADM commands


Add the solution 

stsadm -o addsolution -filename {WSPFILENAME}

Deploy the solution 

stsadm -o deploysolution -name {WSPFILENAME} -url {SITEURL}

Install the feature 

stsadm -o installfeature -filename {FeatureFolder}\feature.xml

Activate the feature 

stsadm -o activatefeature -id {FEATUREID} -url {SITEURL} -force

Deactivate the feature 

Stsadm.exe -o deactivatefeature -filename

Wednesday, May 11, 2011

Auto-Generate number based on location code from another list


public void GenerateInwardNumber(SPItemEventProperties properties)
       {
           try
           {
               int autoid = 101;
               SPWeb oWeb = properties.Web;
               oWeb.AllowUnsafeUpdates = true;
               SPList oList = properties.List;
               SPListItem oItem = properties.ListItem;
               string[] s = Convert.ToString(oItem["Location"]).Split('#');
               string location = s[s.Length - 1];
               SPQuery qry = new SPQuery();
               qry.Query = "<Where><Eq><FieldRef Name='Location1' /><Value Type='Lookup'>" + location + "</Value></Eq></Where><OrderBy><FieldRef Name='Document_x0020_Inward_x0020_Number' Ascending='False' /></OrderBy>";
               SPListItemCollection oItemColl = oList.GetItems(qry);
               string locCode = GetLocationCode(location, properties.Web);
               string oldDIN = Convert.ToString(oItemColl[0]["Document_x0020_Inward_x0020_Number"]);
               string[] str = oldDIN.Split('-');
               if (!string.IsNullOrEmpty(oldDIN))
                   autoid = Convert.ToInt16(str[str.Length - 1]) + 1;
               else
                   autoid = 101;
               SPListItem oCurrItem = properties.ListItem;
               oCurrItem["Document_x0020_Inward_x0020_Number"] = locCode + "-" + autoid;
               this.EventFiringEnabled = false;
               oCurrItem.SystemUpdate(false);
               this.EventFiringEnabled = true;
               oWeb.AllowUnsafeUpdates = false;
           }
           catch (Exception ex)
           {
               properties.ErrorMessage = ex.Message;
           }
       }

       public string GetLocationCode(string location,SPWeb cWeb)
       {
           string locCode="";
           try
           {
               SPQuery locqry = new SPQuery();
               locqry.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + location + "</Value></Eq></Where>";
               SPList locList = cWeb.Lists["Locations"];
               SPListItemCollection oItemColl = locList.GetItems(locqry);
               locCode = Convert.ToString(oItemColl[0]["Location_x0020_Code"]);
           }
           catch (Exception ex)
           {
           }
           return locCode;
       }

Thursday, May 5, 2011

Formatting Date Time in C#



DateTime time = DateTime.Now;
string format = "MMM ddd d HH:mm yyyy";
Console.WriteLine(time.ToString(format));

Tuesday, May 3, 2011

Programmatically getting the metadata information



                SPSite site = new SPSite("http://myserver");
                TaxonomySession txSesssion = new TaxonomySession(site);
                foreach (TermStore store in txSesssion.TermStores)
                {
                    foreach (Group g in store.Groups)
                    {
                        if (g.Name == "GROUP1")
                        {
                            foreach (TermSet tSet in g.TermSets)
                            {
                                if (tSet.Name == "termset1")
                                {
                                    Console.WriteLine("......TermSET : " + tSet.Name);
                                    foreach (Term t in tSet.Terms)
                                    {
                                        Console.WriteLine("TERM :" + t.Name);
                                    }
                                }
                            }
                        }
                    }
                }

Saturday, April 30, 2011

Programmatically adding a document to a document library

  public void AddDoctoLibrary()
        {
            if (FileUpload1.PostedFile != null)
            {
                if (FileUpload1.PostedFile.ContentLength > 0)
                {
                    Stream strm = FileUpload1.PostedFile.InputStream;
                    byte[] byt = new byte[Convert.ToInt32(FileUpload1.PostedFile.ContentLength)];
                    strm.Read(byt, 0, Convert.ToInt32(FileUpload1.PostedFile.ContentLength));
                    strm.Close();
                    // Open site where document library is created.
                    using (SPSite oSite = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb(SPContext.Current.Web.ID))
                        {
                            SPList lstMeetingDocuments = oWeb.Lists["Meeting Documents"];
                            oWeb.AllowUnsafeUpdates = true;
                            SPFile newfile = lstMeetingDocuments.RootFolder.Files.Add(Path.GetFileName(FileUpload1.PostedFile.FileName), byt);
                            SPListItem newItm = lstMeetingDocuments.GetItemById(newfile.Item.ID);
                            newItm["MeetingID"] = lblMID.Text;
                            newItm.Update();
                            lstMeetingDocuments.Update();
                        }
                    }
                }
            }

Thursday, April 28, 2011

Send mail through server object model


public void sendEmail(string mailid)
        {
            try
            {
                SPWeb web = SPContext.Current.Web;
                bool appendHtmlTag = false;
                bool htmlEncode = false;
                string toAddress = mailid;
                string subject = "Comments";
                string message = txtComment.Text;
                bool result = SPUtility.SendEmail(web, appendHtmlTag, htmlEncode, toAddress, subject, message);

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

Get Data from user profile


using Microsoft.Office.InfoPath;
using System;
using System.Xml;
using System.Xml.XPath;
using System.Security.Principal;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;

namespace Form1
{
    public partial class FormCode
    {
        // Member variables are not supported in browser-enabled forms.
        // Instead, write and read these values from the FormState
        // dictionary using code such as the following:
        //
        // private object _memberVariable
        // {
        //     get
        //     {
        //         return FormState["_memberVariable"];
        //     }
        //     set
        //     {
        //         FormState["_memberVariable"] = value;
        //     }
        // }

        // NOTE: The following procedure is required by Microsoft InfoPath.
        // It can be modified using Microsoft InfoPath.
        public void InternalStartup()
        {
            EventManager.FormEvents.Loading += new LoadingEventHandler(FormEvents_Loading);
        }

        public void FormEvents_Loading(object sender, LoadingEventArgs e)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string LoginName = string.Empty;
                    string SiteUrl = SPContext.Current.Site.Url;
                    string UserID = SPContext.Current.Web.CurrentUser.ID.ToString();
                    string EName = string.Empty;
                    string ID = string.Empty;
                    string Mobile = string.Empty;

                    using (SPSite Site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb Web = Site.OpenWeb())
                        {
                            SPList List = Web.Lists["User Information List"];
                            SPQuery Query = new SPQuery();
                            Query.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + Convert.ToInt16(UserID) + "</Value></Eq></Where>";
                            SPListItemCollection ItemCollection;
                            ItemCollection = List.GetItems(Query);
                            if (ItemCollection.Count > 0)
                            {
                                foreach (SPListItem ListItem in ItemCollection)
                                {
                                    EName = Convert.ToString(ListItem["Name"]);
                                    ID = Convert.ToString(ListItem["ID"]);
                                    Mobile = Convert.ToString(ListItem["MobilePhone"]);
                                }
                            }
                            UserProfileManager profileManager = new UserProfileManager(ServerContext.Current);
                            SPUser spUser = Site.RootWeb.Users.GetByID(Convert.ToInt16(UserID));
                            UserProfile profile = profileManager.GetUserProfile(spUser.LoginName);

                            XPathNavigator nav = MainDataSource.CreateNavigator();
                            XPathNavigator txtEName = nav.SelectSingleNode("/my:myFields/my:txtEName", NamespaceManager);
                            XPathNavigator txtEmpID = nav.SelectSingleNode("/my:myFields/my:txtEmpID", NamespaceManager);
                            XPathNavigator txtMobile = nav.SelectSingleNode("/my:myFields/my:txtMobile", NamespaceManager);

                            txtEName.SetValue(EName);
                            txtEmpID.SetValue(profile["EmployeeID"].Value.ToString());
                            txtMobile.SetValue(Mobile);

                        }
                    }
                });
            }
            catch (Exception ex)
            {
            }
        }
    }
}

Wednesday, April 27, 2011

EventListener for autogen number


       public override void ItemAdded(SPItemEventProperties properties)
       {
           try
           {
               if (properties.ListItem.Fields.ContainsField("Document_x0020_Inward_x0020_Number"))
               {
                   int autoid = 0;
                   SPList oList = properties.List;
                   SPQuery qry = new SPQuery();
                   qry.Query = "<OrderBy><FieldRef Name='Document_x0020_Inward_x0020_Number' Ascending='False' /></OrderBy>";
                   SPListItemCollection oItemColl = oList.GetItems(qry);
                   autoid = Convert.ToInt16(oItemColl[0]["Document_x0020_Inward_x0020_Number"]);
                   if (autoid == 0)
                       autoid = 100;
                   SPListItem oCurrItem = properties.ListItem;
                   oCurrItem["Document Inward Number"] = autoid + 1;
                   oCurrItem.SystemUpdate();
               }
           }
           catch (Exception ex)
           {
           }
       }

Wednesday, February 16, 2011

Activating and Deactivating Features with PowerShell in SharePoint 2010


I was looking at the analytics of the site the other day and I noticed that my post, Adding and Deploying Solutions with PowerShell, currently has the most traffic on the site.  I had always intended to write a follow up post on this, so here it is.  Today I’m going to talk about how to enable and disable features using PowerShell.  It’s great that you know how to deploy solutions now with PowerShell, but now you want to activate your features.In SharePoint 2007 to activate a feature from the command line you might have used a statement like the one below.  I’ll use the Reporting feature on my server named sp2010 as an example.  The value specified in the name parameter refers to the actual folder name of the feature that is in your SharePoint Root folder (14 hive).

stsadm.exe –o activatefeature –name Reporting –url http://sp2010
To get started with PowerShell, run the SharePoint 2010 Management Console located in your Microsoft SharePoint 2010 Products folder on your start menu.  This automatically loads the Microsoft.SharePoint.PowerShell snapin so that we can execute SharePoint commands.    You might have noticed earlier that I said we will talk about enabling and disabling features.  The words enable and disable are key here because PowerShell uses those verbs to activate and deactivate features.  To issue the same command above but with PowerShell, we use the Enable-SPFeature command.  The rest of the syntax is pretty similar as you can see below.  Just use –Identity to specify the name of the feature.  You can even pass the –Force command like you could with stsadm.exe.
Enable-SPFeature –Identity Reporting –url http://sp2010
If your command worked successfully, you will see nothing and just get a blank prompt back.
PowerShellEnableSPFeatureNoOutput
If you would like to get some feedback from the command, you can have it return the SPFeature object back to you by specifying the –PassThru parameter.
PowerShellEnableSPFeaturePassThru
We can confirm that the feature did in fact activate successfully using the SharePoint UI.
PowerShellReportingFeatureEnabledUI
Can we confirm that the feature is enabled with PowerShell?  Yes, we can by using Get-SPFeature.  Now this cmdlet behaves differently depending upon the parameters passed through it.  For example, if you type the following, it lists every feature on the SharePoint farm along with its Id and Scope.
Get-SPFeature
However, if you want to know which features are enabled, you can pass it a URL for a given scope (i.e.: –Web, –Site, –WebApplication, and –Farm).  So to get a list of all Site Collection scoped features, we would use the –Site parameter.
Get-SPFeature –Site http://sp2010
PowerShellGetSPFeatureSite
You can still specify a specific feature or even use Where-Object to query the list as well.
Get-SPFeature –Identity Reporting –Site http://sp2010
PowerShellGetSPFeatureSiteSpecific
If you get something like you see in the screenshot above, you know the feature has been activated.  When the feature hasn’t been activated, you will get a lovely red error message.
PowerShellGetSPFeatureSiteSpecificNotEnabled
The Enable-SPFeature command can also take a Pipe Bind from Get-SPFeature.  This means that you could even activate multiple features at once this way.  I’ll include an example of this in the future.
At some point, you will want to disable that feature you activated.  As you probably guessed, the cmdlet you want is Disable-SPFeature.  You use the same parameters that you use with Enable-SPFeature.  When you execute the command, it prompts for confirmation as you can see in the screenshot.
Disable-SPFeature –Identity Reporting –url http://sp2010
PowerShellDisableSPFeatureWithConfirmation
If you want to disable confirmation, you can pass the –confirm:$false parameter.
Disable-SPFeature –Identity Reporting –url http://sp2010 –Confirm:$false
PowerShellDisableSPFeatureNoConfirmation
Setting the confirm parameter eliminates the confirmation prompt and you can use it with other PowerShell cmdlets as well.  That is all that is involved in activating and deactivating features with PowerShell.  It’s pretty easy.   Hopefully, you can incorporate these commands in your deployment scripts.

Adding and Deploying Solutions with PowerShell in SharePoint 2010


Visual Studio 2010 makes it really easy to add and deploy solutions when you are developing, but you may eventually want to deploy those solution packages elsewhere right?  We can still use stsadm, but that is effectively considered deprecated now in favor of PowerShell.  In the past to add a solution, we used an stsadm command like the one below.  In today’s example, we’ll be working with a package called SharePointProject2.wsp on my server named sp2010.
stsadm –o addsolution –name SharePointProject2.wsp
To get started with PowerShell, run the SharePoint 2010 Management Console located in your Microsoft SharePoint 2010 Products folder on your start menu.  This automatically loads the Microsoft.SharePoint.PowerShell snappin so that we can execute SharePoint commands.  To install a solution we use the Add-SPSolution command.  If you are using a Sandboxed solution you would use Add-SPUserSolution instead.  It takes just one parameter, –literalpath, which is the path to the solution file.  One thing that is different is that you must specify the full path to the file for some reason.  I haven’t been able to get it to take a path to the solution in the current folder even if I make use of .\ before the filename.  Here is an example.
Add-SPSolution c:\code\SharePointProject2\bin\debug\SharePointProject2.wsp
In this case you don’t actually have to type –literalpath before the parameter.  This is what it looks like when executed.  You can see that it displays the id of the solution along with its deployment status.
PowerShellAddSolution
Now we need to deploy the solution.  In the past, we used an stsadm command like the following.
stsadm –o deploysolution –name SharePointProject2.wsp –url http://moss-server –allowCasPolicies –immediate
We would also follow this up with a call to stsadm with the execadmsvcjobs operation.  To do the same operation in PowerShell, we use the Install-SPSolution command (again use Install-SPUserSolution for Sandboxed solutions).  You can use the Get-Help command (i.e.: Get-Help Install-SPSolution) to get more information on a command but it’s not always obvious what it is expecting as you can see below.  That is why I am writing the post today.
PowerShellGetHelpInstallSolution
The first parameter you need is the –Identity parameter.  This is the name of the solution package (i.e.: MySolution.wsp).  Depending on if you are using the GAC or Code Access Security, you will specify either –GACDeployment or –CASPolicies.  You then need to specify a specific web application using the –WebApplication parameter or –AllWebApplications to deploy it to all web applications (assuming the manifest allows it).  If you need to force the deployment, you can still use the –Force command.  Here is what an install command might look like.
Install-SPSolution –Identity SharePointProject2.wsp –WebApplication http://sp2010 -GACDeployment
I’ll point out that executing this command actually does do the deployment operation.  You don’t have to fire off something to execute a job later like you did with stsadm.
You might want to update your solution, so we’ll talk about how to do that as well.  Here is what your stsadm command might have looked like in WSS3.  Which would also be followed up with an execadmsvcjobs operation.
stsadm –o upgradesolution –name SharePointProject2.wsp –filename SharePointProject2.wsp –immediate –allowCasPolicies
The upgrade solution syntax is similar to the others.  We just have to specify an identity and a literalpath with the Update-SPSolution command.  The identity is the name of the package on the server to upgrade and the literalpath is the full path to the new solution package on the file system.  Here is what that might look like.
Update-SPSolution –Identity SharePointProject2.wsp –LiteralPath c:\code\SharePointProject2\bin\debug\SharePointProject2.wsp –GACDeployment
We’ve talked about everything else, so we’ll finish it up by talking about retraction and removal.  To retract a solution we use the Uninstall-SPSolution command.  By now you are probably noticing a pattern in the way things are named.  Install –> Deploys, Uninstall –> Retracts.  It also just uses the -Identity parameter and the –WebApplication parameter.  You can also use the –AllWebApplications parameter to retract it from all web applications. Many of these commands may prompt you with an “Are you sure?” type prompt.  You can skip this prompt by adding a –confirm parameter.  Here is what it looks like.
Uninstall-SPSolution –Identity SharePointProject2.wsp –WebApplication http://sp2010
Lastly, to remove the package from the solution store, we use the Remove-SPSolution command.  It just takes the name of the package.
Remove-SPSolution –Identity SharePointProject2.wsp
I hope this helps.  If you’re like me, it’s one thing to see the docs on something, but I like to see real examples.  There aren’t any examples in the Get-Help command yet.  This should cover all of the common commands that you probably used to used with stsadm in regards to solution deployment.  The nice thing is that you can script these things together very easily and create highly flexible PowerShell scripts.  Expect a few more posts soon on the basics of working with PowerShell and SharePoint 2010.