Sunday, April 29, 2012

How to Integrate Syntaxhighlighter with SharePoint?

Needless to say, format and style of our code plays vital part when writing technical blogs. Among the other code formatting plugins, I personally like SyntaxHighlighter(http://alexgorbatchev.com) as it is very easy to configure and use while keeping the code readable and easy to copy.

In this article I'm sharing my experience on integrating syntax highlighter with SharePoint 2010.

Step 1: Download the SyntaxHighlighter & upload to SharePoint
Download the syntax highlighter from http://alexgorbatchev.com/SyntaxHighlighter/download/ and upload the files to a document library (or on the SharePoint server's 14 hive) so that you can reference them. Here I've created a document library with name "Syntax"
syntaxhighlighter sharepoint 2010

Step 2:Link/Refer the CSS and JS files
You can either refer the CSS & JS files in your Master page (Recommended) so that you wan to use it for anywhere.Or if its for one time, You can refer the files in content editor webpart even.
  • Go to SharePoint Designer, Open your site
  • Edit your Master page in advanced mode
  • Search for
<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server"/>
  • and Place this code just below, in Master page
syntaxhighlighter in sharepoint

<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server"/>
<!-- Reference for CSS files from current site collection -->
<SharePoint:CssRegistration name="<%$SPUrl:~SiteCollection/Syntax/shCore.css%>" runat="server"/>
<SharePoint:CssRegistration name="<%$SPUrl:~SiteCollection/Syntax/shThemeDefault.css%>" runat="server"/>
<!-- Reference for Js files  -->
<SharePoint:ScriptLink language="javascript" name="~sitecollection/Syntax/shCore.js" Defer="true" runat="server"/>
<SharePoint:ScriptLink language="javascript" name="~sitecollection/Syntax/shBrushCSharp.js" Defer="true" runat="server"/>
<!-- Call the script to apply formatting -->
<script type='text/javascript'>SyntaxHighlighter.all();</script>


OR If you want to refer from file system:
<!--This will search Shcore.js file in "14/template/layouts/1033/syntax/shcore.js"-->
<SharePoint:ScriptLink ID="ScriptLink1" Name="/Syntax/shCore.js" runat="server"/>
<SharePoint:ScriptLink ID="ScriptLink2" Name="/Syntax/shBrushCSharp.js" runat="server"/>
<!-- Call the script to apply formatting -->
<script type='text/javascript'>SyntaxHighlighter.all();</script>


If its for one time, You can just place these references in Content Editor webpart.
Add a content editor, Place this code. once done, Hide this content editor webpart.
<link href="/Syntax/shCore.css" rel="stylesheet" type="text/css"/>
<link href="/Syntax/shThemeDefault.css" rel="stylesheet" type="text/css"/>
<script src="/Syntax/shCore.js" type="text/javascript"></script>
<script src="/Syntax/shBrushCSharp.js" type="text/javascript"></script>
<!-- Call the script to apply formatting -->
<script type='text/javascript'>SyntaxHighlighter.all();</script>

Check-in and Publish your master page.

Step 3: Use the <Pre Class> wherever required.

<pre class="brush:c#"> YOUR CODE GOES HERE</pre>
syntaxhighlighter sharepoint blog

You will get Output like this when you place some more code: Syntaxhighlighter in SharePoint wiki
syntaxhighlighter sharepoint wiki

Note: Here I've added the core functionality to highlight the code and the highlighting color brush for C# code only. For other code types, you add the appropriate brushes as separate references.


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


Friday, April 27, 2012

How to Programmatically Upload File to SharePoint Document Library?

Code snippet to programmatically upload Files to SharePoint List or Library:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.IO;
using System.Collections;

namespace UploadFiles
{
    class Program
    {
      static void Main(string[] args)
        {
          //Get the Site collection
            using (SPSite site = new SPSite("http://sharepoint.com"))
            {
                //Open the Root web
                using(SPWeb web=site.OpenWeb())
               {
                /*** Simple File Upload ********/
                // Read the file from the stream into the byte array
                FileStream fs= File.OpenRead(@"c:\MyDoc.doc");
                byte[] FileContent= new byte[fs.Length];
                fs.Read(FileContent, 0, Convert.ToInt32(fs.Length));
                fs.Close();
                //Get the documents Librarym named "Documents"
                SPList DocLib = web.Lists["Documents"];
                //Add the file
                web.Files.Add(DocLib.RootFolder + "/MyDoc.doc", FileContent, true);

                /*** If you want to add inside a folder: say "Sales" *******/
                // Get the folder called "Sales"
                SPFolder SubFolder = DocLib.RootFolder.SubFolders["Sales"];
                //Add the file to the sub-folder
                SPFile file = SubFolder.Files.Add(SubFolder.Url + "/MyFile.doc", FileContent, true);
                SubFolder.Update();

                //IF you want to Update the Meta data column say "Country"
                SPListItem item = DocLib.Items[file.UniqueId];
                item["Country"] = "Denmark";
                item.Update();
                // OR We can use the Hash Table
                var Metadata = new Hashtable { { "Country", "India" } };
                // Add the file
                web.Files.Add(DocLib.RootFolder + "/MyDoc2.doc", FileContent, Metadata, true);

                /**** Check-in the file, If the Library has mandatory Columns or Explicit Check-out Enabled *******/
                if (file.CheckOutStatus != SPFile.SPCheckOutStatus.None)
                {
                    file.CheckIn("File uploaded Programmatically !");
                }

                /**** Publish the file using File.publish() method If Minor versions enabled! ****/
                //file.Publish("File published Programmatically !");

              }
            }

        }
    }
}



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


Thursday, April 26, 2012

SharePoint Site Template IDs Reference

When you create SharePoint sites, you'll be picking a relevant template from number of available ones. So, SharePoint makes it easier rather developing everything from the scratch. If you create a SharePoint site/web using PowerShell, You need the template code or id to provision.

How to get SharePoint Site/Web Templates using PowerShell:
To get all available site templates in SharePoint with the PowerShell, use this cmd-let:  
Get-SPWebTemplate
This lists all available templates in the farm. Here is the SharePoint site template codes:
Template Name Description
GLOBAL#0 Global
STS#0 Team
STS#1 Blank
STS#2 Document
MPS#0 Basic
MPS#1 Blank
MPS#2 Decision
MPS#3 Social
MPS#4 Multipage
CENTRALADMIN#0 Central
WIKI#0 Wiki
BLOG#0 Blog
SGS#0 Group
TENANTADMIN#0 Tenant
ACCSRV#0 Access
ACCSRV#1 Assets
ACCSRV#3 Charitable
ACCSRV#4 Contacts
ACCSRV#6 Issues
ACCSRV#5 Projects
BDR#0 Document
OFFILE#0 (obsolete)
OFFILE#1 Records
OSRV#0 Shared
PPSMASite#0 PerformancePoint
BICenterSite#0 Business
SPS#0 SharePoint
SPSPERS#0 SharePoint
SPSMSITE#0 Personalization
SPSTOC#0 Contents
SPSTOPIC#0 Topic
SPSNEWS#0 News
CMSPUBLISHING#0 Publishing
BLANKINTERNET#0 Publishing
BLANKINTERNET#1 Press
BLANKINTERNET#2 Publishing
SPSNHOME#0 News
SPSSITES#0 Site
SPSCOMMU#0 Community
SPSREPORTCENTER#0 Report
SPSPORTAL#0 Collaboration
SRCHCEN#0 Enterprise
PROFILES#0 Profiles
BLANKINTERNETCONT... Publishing
SPSMSITEHOST#0 My
ENTERWIKI#0 Enterprise
SRCHCENTERLITE#0 Basic
SRCHCENTERLITE#1 Basic
SRCHCENTERFAST#0 FAST
visprus#0 Visio


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


Tuesday, April 24, 2012

SharePoint My Site Analysis Report - A Practial Business Scenario

Call from my CIO: "Salaudeen, I need the SharePoint 'My Site' Report with Department wise users along with their other details such as E-Mail."

Well, E-Mail I can retrieve by querying Site Owner object, How about Department? Ah, Its available in Profile DB. Let me query that.

Here is my code:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;
using System.Web;

namespace SharePoint.AdminReports
{
    class MySiteAnalysis
    {
        static void Main(string[] args)
        {

            //Get the My Site web application URL
            string site;
            string WorkEmail;
            if (args.Length == 0)
            {
                Console.WriteLine("Enter the My site URL:");
                site = Console.ReadLine();
            }
            else
            {
                site = args[0];
            }

            //objects for the CSV file generation
            StreamWriter SW;
            SW = File.AppendText("c:\\SiteOwnersReport.csv");
            //Write the CSV Header
            SW.WriteLine("Site URL, Owner Name, E-Mail, Department");

            try
            {
                SPSite tmpRoot = new SPSite(site);
                SPSiteCollection tmpRootColl = tmpRoot.WebApplication.Sites;

                //Enumerate through each site collection
                foreach (SPSite tmpSite in tmpRootColl)
                {
                    try
                    {
                        WorkEmail = tmpSite.Owner.Email;
                    }
                    catch (NullReferenceException ex1)
                    {
                        WorkEmail = string.Empty;
                    }

                    SW.WriteLine(tmpSite.Url + "," + tmpSite.Owner.LoginName + "," + WorkEmail + "," + GetDepartment(site, tmpSite.Owner.LoginName));
                }
                //Dispose the objects
                SW.Close();
                SW.Dispose();
                tmpRoot.Dispose();

            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Site Owner Report", ex.Message);
            } 
            }


        //Method to Get the department of the Site owner
        private static string GetDepartment(string siteURL, string loginName)
        {
            string Department;
            try
            {
                
                using (SPSite site = new SPSite(siteURL))
                {
                    // if the Profile not found in Profile store, SharePoint will throw: UserNotFoundException exception
                    try
                    {
                        ServerContext context = ServerContext.GetContext(site);
                        UserProfileManager profileManager = new UserProfileManager(context);
                        UserProfile profile = profileManager.GetUserProfile(loginName);

                        //Department may or May not be associated.
                        try
                        {
                            Department = profile["Department"].Value.ToString();
                        }
                        catch (NullReferenceException ex2)
                        {
                            Department = string.Empty;
                        }
                    }
                    catch (UserNotFoundException ex3)
                    {
                        Department = "** User not Found **";
                    }
                }
            }
            catch (Exception ex4)
            {
                Department = string.Empty;
            }
            return Department;
        }
    }
} 
 
and the code brings the Report in CSV format:
SharePoint My Site Analysis

By the way, This report also gives "Orphaned Mysites" information also. Since I've disabled "Site usage confirmation and deletion" feature, it resulted orphaned my sites.

Tail: 
In case you don't have dedicated web application for My Site (which is bad, in-fact) you can check the "WebTemplate" Property of SPWeb object. My Site's web template is: "SPSPERS"

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


How to Hide User Name in SharePoint Survey

Ever wanted to hide the user identity in SharePoint Survey? Recently, to provide complete anonymity, we had to hide the user names in Created by and Last Modified By fields in a SharePoint Survey.

Follow these steps to hide user names in SharePoint survey:
  1. Go to your SharePoint Survey page
  2. Click on Settings >> Survey Settings
  3. Click on Title, description and navigation link Under General Settings sharepoint survey hide created by
  4. Under Survey Options, select No for Show user names in survey results?
    sharepoint survey hide user name
  5. Click on Save button to apply the changes.
Now, you will see fields like Created By and Last Modified By appear as *** instead of the actual user name.
sharepoint 2010 survey remove created by
If you want to know who answered the survey, enable "Show user names in survey results" and this will reveal user names again!

Although other lists doesn't provide a way to hide user names, we can achieve it programmatically. refer: How to Hide User Names in Created by, Modified by Fields in SharePoint

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


Sunday, April 22, 2012

Apply Filters to People Picker in SharePoint - E.g. Don't show User Accounts with No E-mail

Business Problem:
Many users having more than one account/admin account in multiple domains. Now the problem is: when end-users selects approvers from people pickers in various workflows, They selects user account without E-Mail. Since the workflows are unable to get any E-Mails from the selected users they are failing.
filter people picker in sharepoint

What's the Solution: Lets instruct People Picker "O.K, People Picker, Don't show me accounts which doesn't has E-Mail associated!"

But How to filter people picker in SharePoint? Set the appropriate People Picker custom Properties by running the below STSADM commands:

Lets say, you want only the "Sales" or "IT" department people to be in People picker. Just apply the filter to People picker with STSADM:

stsadm -o setproperty -pn peoplepicker-searchadcustomfilter -pv "(|(department=Sales)(department=IT))" -url <web-application-URL or Site collection URL>

To Filter-out accounts without E-mails:
stsadm -o setproperty -pn peoplepicker-searchadcustomfilter -pv "(|(mail=*)(objectcategory=group))" -url <web-application-URL or Site collection URL>

Here, I've added (objectcategory=group) with OR condition, since security groups wont be having E-Mails usually.
  • Get rid of Disabled accounts and get users from only a particular Forest/Domain?
stsadm -o setproperty -pn peoplepicker-searchadcustomfilter -pv "(&(userPrincipalName=*crescent.org)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))" -url <web-app-url or Site-collection-URL>

  • Filter-out accounts without E-mails, Disabled Accounts and Get Accounts only from a Particular Domain further:
stsadm -o setproperty -pn peoplepicker-searchadcustomfilter -pv "(|(&(mail=*)(userPrincipalName=*crescent.org)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))(objectcategory=group))" -url <web-application-URL or Site collection URL>

Restrict People Picker on a Site Collection within a specific OU in Active Directory:

  • SharePoint 2010 / 2007 people picker filter domain:
Need users ONLY from a OU/Domain for a site collection?
stsadm -o setsiteuseraccountdirectorypath -path "CN=Sales,DC=ME,DC=CRESCENT, DC=org" -url http://company.intranet.com/sites/sales

PowerShell:  Set-SPSite -Identity "http://intranet.crescent.com" -UserAccountDirectoryPath "CN=Sales,DC=Crescent,DC=com"
  • Clear People Picker Filters (Undo)
stsadm -o setsiteuseraccountdirectorypath -path "" -url http://company.intranet.com/sites/sales

PowerShell: Set-SPSite -Identity "http://intranet.crescent.com" -UserAccountDirectoryPath ""
  • Get the current filters applied:
stsadm -o getproperty -url <web-application-URL or Site collection URL> -pn peoplepicker-searchadcustomfilter  


Important:
Clear any existing properties applied. E.g:
  • stsadm -o setproperty -pn peoplepicker-searchadcustomfilter -pv " " -url <web-application-URL>
  • stsadm -o setproperty -pn peoplepicker-searchadcustomquery -pv " " -url <web-application-URL>
Last but not least:
Remember: People picker gets its data both from Active directory and from the "User Information List" of the site collection. So make sure you are cleaning up both!

Above people picker search filters applies to both SharePoint 2010 and SharePoint 2007.

PowerShell to get People Picker Settings:
You can use PowerShell too:
$webApp = Get-SPWebApplication 'Web-App-Name or URL'
$webApp.PeoplePickerSettings
E.g. Lets set custom filter in People Picker using PowerShell:
$WebApp = Get-SPWebApplication http://web-App-Url
$WebApp.PeoplePickerSettings.ActiveDirectoryCustomQuery = "(|(mail=*)(objectcategory=group))"
$WebApp.Update()

Technet Reference: http://technet.microsoft.com/en-us/library/cc263318%28v=office.12%29.aspx
Learn the LDAP Query basics: http://technet.microsoft.com/en-us/library/aa996205%28EXCHG.65%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, April 20, 2012

Branded Master Page & Page Layout Project in MOSS 2007

This is the Custom Branded Master page & Page layout project, I've worked long back for a Event oriented SharePoint Site built on MOSS 2007. 

Page Layout in Design Mode:

Page in Browser:

 
   

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


Thursday, April 19, 2012

Delete Users and Clean up User Information List

Some time back, I wrote an article on deleting user accounts from "User Information List" to get rid of the issue: Deleted accounts shown in People Picker: SharePoint People Picker shows deleted accounts in Active Directory and SharePoint

Since the people picker get data from both Active directory and "User Information List" of SharePoint (Which is a hidden list - SharePoint will create an entry in this list when the user added to the site or visits the site for the first time. SharePoint sync this list from user profile when user create/edit/update/delete items).

In my organization, for some reasons, management decided to remove a particular domain completely. So the requirement turned towards SharePoint as: Remove All users of particular domain from User Information List, so that those accounts will not be visible in People picker! By the way, those accounts were already deleted from active directory and from SharePoint user profile import connections. So, I've to delete user from sharepoint user information list.

Now, I wish to generate a report with all the users from User Information List, in order to identify and remove users of the particular domain from various site collections. Wrote the below code using Object Model before delete user from user information list.

To Generate Report on All Users from User Information List:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;

namespace UserInformationListReport
{
    class Program
    {
        static void Main(string[] args)
        {
            string site;
            string EmailID=string.Empty;
            string UserName = string.Empty;

            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Enter the Web Application URL:");
                    site = Console.ReadLine();
                }
                else
                {
                    site = args[0];
                }

                //objects for the CSV file generation
                StreamWriter SW;
                SW = File.AppendText("c:\\UserInfoListReport.csv");
                //Write the CSV Header
                SW.WriteLine("Site collection Name, Site collection URL,  Account, User Name, E-Mail");

                SPSite tmpRoot = new SPSite(site);
                SPSiteCollection oSPSiteCollection = tmpRoot.WebApplication.Sites;

                //Enumerate through each site collection
                foreach (SPSite oSPSite in oSPSiteCollection)
                {
                  SPWeb oSPWeb = oSPSite.OpenWeb();
                  SPList oSPList = oSPWeb.SiteUserInfoList;

                      foreach (SPItem oSPItem in oSPList.Items)
                     { 
                      //For Deleted accounts, it may result NULL. So catch it.
                         try
                         {
                             // Set the variables
                            EmailID = oSPItem["Work e-mail"].ToString();
                            UserName = oSPItem["User name"].ToString();
                         }
                         catch (Exception ex2)
                         {
                             EmailID=string.Empty;
                             UserName = string.Empty;
                         }

                       //Log them to a file and delete - Field Names are case sensitive
                         SW.WriteLine(oSPWeb.Title.Replace(",", " ") + "," + oSPSite.Url + "," + oSPItem["Account"] + "," + UserName+ "," + EmailID);
                     }
                 }  

            //To Pause
            Console.WriteLine("Report has been Generated! Press a key to exit");
            Console.ReadLine();
            //Dispose of the bjects
            SW.Close();
            }

            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("User Information List Report", ex.Message);
            } 
        }
    }
}


To Remove users of a Particular Domain from SharePoint User Information List: (say the domain to be removed is: EMEA)

static void Main(string[] args)
        {
            string siteCollectionURL;
            string EmailID = string.Empty;

            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Enter the Site Collection URL:");
                    siteCollectionURL = Console.ReadLine();
                }
                else
                {
                    siteCollectionURL = args[0];
                }

            //objects for the CSV file generation
            StreamWriter SW;
            SW = File.AppendText("c:\\DeletedUsersFromUserInfoList.csv");
            //Write the CSV Header
            SW.WriteLine("Account, E-Mail");

            using(SPSite oSPSite=new SPSite(siteCollectionURL))
            {
                SPWeb oSPWeb = oSPSite.OpenWeb();
                SPQuery oSPQuery = new SPQuery();

                //Filter the EMEA Domain
                oSPQuery.Query = "<Where><Contains><FieldRef Name='Name' /><Value Type='Text'>EMEA</Value></Contains></Where>";
                SPList oSPList = oSPWeb.SiteUserInfoList;
                SPListItemCollection oSPListItemCollection = oSPList.GetItems(oSPQuery);
                
               /* To get the available Fields in the User Information List
                SPItem oSPItem = oSPList.Items[1];
                    for (int i = 0; i < oSPItem.Fields.Count; i++)
                    {
                    SW.WriteLine(oSPItem.Fields[i].Title + ",");
                    }
               */

                foreach (SPItem oSPItem in oSPListItemCollection)
                {
                    //For Deleted accounts, it may result NULL. 
                    try
                    {
                        // Set the variables
                        EmailID = oSPItem["Work e-mail"].ToString();
                    }
                    catch (Exception ex2)
                    {
                        EmailID = string.Empty;
                    }

                    //Log them to a file and delete - Field Names are case sensitive
                    SW.WriteLine(oSPItem["Account"] + "," + EmailID);

                    //Delete the User
                    oSPWeb.AllowUnsafeUpdates = true;
                    oSPWeb.SiteUsers.RemoveByID((int)oSPItem["ID"]);
                    oSPWeb.Update();
                    oSPWeb.AllowUnsafeUpdates = false;
                }
                
            }  

            //To Pause
            Console.WriteLine("Users deleted and Log has been Generated! Press a key to exit");
            Console.ReadLine();
            //Dispose of the bjects
            SW.Close();
            }

            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Remove From User Information List", ex.Message);
            }
        }
This code will delete all users from user information list in SharePoint 2010 (or in SharePoint 2007).

Delete Users from User Information List using SharePoint UI:
If there are only few accounts to be deleted, then you can navigate to "Site actions >> Site settings >> All People (_layouts/people.aspx)" to remove users from site collection. By the way, this application page pulls users from user information list only!

Remove Deleted users from People Picker with PowerShell:
Here is the PowerShell script to remove deleted users from SharePoint people picker: SharePoint People Picker Showing Deleted Users? Remove with PowerShell

If you want to update existing profile in User Information List, You can use "Set-SPUser" cmd-let as in http://blog.falchionconsulting.com/index.php/tag/set-spuser/


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


Monday, April 16, 2012

People Picker not Showing All Users from Active Directory Domain?

In a Sandbox, Installed and configured SharePoint. Everything works great, except the People Picker. Problem is: People picker didn't show any user from active directory, However it showed me the users from my local sandbox. Verified whether the Sandbox is joined to the domain. Yes, It is. 

sharepoint 2010 people picker not showing all domain users
By default, People picker should show accounts from AD where the server belongs to. It also will get the users from Two-way-Trusted domains. (And of course, from the site collection's "User Information List" as well.) Additional configurations are needed in case of Configure People Picker in One-way-trusted domains.

But here, Application Pool account is the culprit: The application pool account is the one which pulls users from AD to People Picker and in my case, the application pool account was a local account, not a member in AD. App pool id must be a Domain user!

Well, After changing the application pool account from local account to the domain account, able to get the active directory users in People Picker. Other things to check: Alternate access mappings and check if any custom people picker properties are set.

BTW, If you want to restrict people picker to get users ONLY with in the site collection, You can set the property peoplepicker-onlysearchwithinsitecollection !
stsadm -o setproperty –url <web-app-URL> –pn peoplepicker-onlysearchwithinsitecollection –pv yes

To Check whether its applied or not:
stsadm -o getproperty –url <web-app-URL> –pn peoplepicker-onlysearchwithinsitecollection

SharePoint 2010 people picker not showing all users? Check any filters applied to people picker: Apply Filters to People Picker - E.g. Don't show me Accounts without E-mails


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


Sunday, April 15, 2012

PowerShell Quick Reference for SharePoint Administrators

What is PowerShell?
PowerShell is a command-line scripting tool that helps you to automate and quickly solve tedious Administrator tasks. It was originally developed by Microsoft for task automation and configuration management purposes. PowerShell combines the Power of command-line shell and scripting language!

PowerShell also provides an administrator full access to COM, WMI and supports API calls from several applications, Such as:
  • SharePoint
  • Exchange Server
  • Windows Desktop OS, Server OS
  • SQL Server
  • SCOM/SCDPM/SVCMM
  • VMWARE/Citrix 
  • Office 365, Azure, etc.
PowerShell runs on top of .NET framework, 2.0+. With PowerShell, we can automate almost every thing we do with GUI (some times, things which are not possible with GUI). Its not just command prompt or Script language, But its a Command-Shell, just like DOS shell, But more powerful.

Problems with Existing scripting languages
  1. No common scripting for all the products
    • .Net code
    • COM Model
    • Exe
    • VBScript
  2. Scripts are really security concern, because they do have lot of power
    • Echo “Welcome”
    • Del *.* ???
  3. Top Concerns:
  • Integrity
  • Identity
  • Double click Run
  • Command Hijacking
PowerShell addresses this issue by introducing Executing Policy

PowerShell’s Execution Policy
  1. Restricted - No scripting allowed
  2. Unrestricted - You can any scripting
    • No signing required
  3. Remote signed – good for Test, Dev environments
    • Only files from internet need to be signed
    • This is the default setting
  4. All signed  - local, remote script, it should be signed.
    • user must agree to run script
To change the Execution Policy you can execute the Set-ExecutionPolicy RemoteSigned  from PowerShell command window. This in fact sets the registry key: HKLM\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell

IDEs:
  1. ISE – PowerShell 2.0, built-in. you can fire it by typing PowerShell_ISE in run box!
  2. PowerGUI - Open source yet powerful, I Love it! FREE.
  3. Powershell +
Cmdlets
Cmdlets are built-in commands for PowerShell. Heart and Soul of PowerShell or Engine that make PowerShell work. They are the small units of functionality that perform the operations. will be in
"verb-noun" names.
E.g.  Get-Childitem
   Get-help
       Get-Command  - Lists all available cmdlets

Cmdlets are extensible. We can write own cmdlets.

Basic Tour: Help, Process, Services & Event log:
Getting help in PowerShell
E.g.
Get-Help
Get-Help –verb get
Get-Help –noun file
Get-help  stop-process –examples
Get-help  stop-process –full
Get-help SP*

Basic cmdlets for process, services
Ask for Help: Help *process*
E.g. Get-process –name calc
Get-process  can be called by its Alias PS

How to get the available properties & methods of a cmdlet?
Use: Get-process | get-member
Stop-process -> Alias Kill
Stop-process –name calc
Stop-process –name calc –whatif

Services Cmdlets
Get-service <service name>
Restart-service <service name>
Stop-service <service name>
Get-service –include “Sharepoint*”
Get-service –exclude “Sharepoint*”

Event log: 
Get-eventlog
Eg. get-eventlog system –newest 10
Get-eventlog | -newest 10 format-list


Variables
PowerShell assigns best suited data type for variables when assigned. Variables start with $ sign.
New-variable  -name var –value 10
Remove-Variable –name var

Or
$var=10

PowerShell Supports Int, DateTime, Bool, String, Char, Byte, decimal, array, XML data types. Variables are actually .net objects.
$Test="Crescent"
We can use $Test.toUpper() to get the upper case of the string $Test. Use Get-Member to retrieve all the member of the object. If you have to force the data, you can use:[string]$var=5
$var.gettype().fullname

Variables Can be strongly typed. E.g.
[string]$text = "Text Value goes here" 


Boolean/Null variables:Set a Variable to: true
$Completed = $true

To Check if a Variable is true
If ($completed -eq $true)
{
  #Do something
}

Check for Null:
If ($Completed –eq $null)
{
  #Do something
}

Pipelines
Commands manipulates and passes objects from One to another
 E.g: Get the list of process > filter > stopped Process > format the output to screen
Get-process | where-object {$_.status –eq “Stopped”} |format-list
Get-process | out-file C:\process.txt
Get-process | out-Printer <Name of the printer>

Read/Write to Screen:

Write-Host "Hello World!" –foregroundcolor "green"

$name = Read-Host "Enter your name"
Write-Host "Hello" $name


Write-output Vs write-host
First one sends output to the pipeline, Second doesn’t
Write-output “Hello” |where-object {$_.length – gt 2}
We have some additional options like –foregroundcolor


Operators
All Basic math operations: +, -, *, /, %
5+5; 10-1; 8*2; 10%3; 5+(5*5)

Comparison:
Comparison operators list:
-lt Less than
-le Less than or equal to
-gt Greater than
-ge Greater than or equal to
-eq Equal to
-ne Not equal to
-like Like (uses wildcards for matching)
-notlike Not like (uses wildcards for matching)

Equal to: EQ
Not Equal to: NE
10 –eq 5
LT, -GT, -GE, -LE
String comparison: not case sensitive
“Hello” – eq “HELLO” > true
Forcing case sensitive:
“Hello” – ceq “HELLO” > true
Logical operators
AND OR NOT

Sort – Measure –Select - Compare- filter
Sort
Get-process | sort-object VM –desc
Get-service |sort status
Measure
Get-service |measure-object
Get-service |measure-object –property VM –sum –min-max –average
Select
Get-service | select-object displayname,status
Get-process | select-object –first 10
Compare:
$p1=get-process
Now open a new process, say calc
$p2=get-process
Compare-object $p1, $p2 –property name

Export-Import and compare
Export-CSV
Get-process | Export-csv
Import-CSV
$Process=import-csv c:\sa.csv

Logical constructs

IF, Switch, For, While
IF, Switch – Decision. For, while – looping

if($var –gt 100)
 { 
  write-host “yes”
 }
  elseif()
  {
   //do something
  }
  else
 {
  //do something else
 }

Switch
E.g.

$company =“Crescent”
Switch($var)
{
“Microsoft” {write-host “Microsoft”}
Crescent” {write-host “Crescent”}
Default {write-host “Not in list”}
}


While, Do..while, Do.. Until:
$var=1
While($var – lt 10)
    {
        write-host $var
        $var++
    }
 
Do-While:
$a=1
Do {$a; $a++}
While($a –lt 10)


Do-Until:
$a=1
Do {$a; $a++}
Until($a –gt 10)


For-each
$services=Get-Service
Foreach($x in $services)

   write-host $x.name.ToUpper()
}

For-Loop:
For ($i=1; $i -le 10; $i++)
{
    write-host $i
}


Script Block
Executes the block of code from file, variable
$b={write-host “Hello”}
$b >>write-host “hello”
To Execute : &$b

Functions:

E.g.  
Function sayHello()
{
  write-host “Hello”
}
sayHello
 
E.g. 
Function sayHello($SenderName)
{
  write-host “Hello” + $senderName
}
sayHello “Crescent

SayHello “Crescent” -> write-host “Hello” $args[0]

Return statement:
function determine
{
 if($var – gt 10)
 {
  return $true
  }
  Else
  {
  return $false
  }
}

Comments:
Single line comment : #comment
Multi-Line:
<#
Multiline Comments
Can be placed inside
comment block
#>

Regular expressions
 Regular expressions is the standard for Pattern matching. In PowerShell we have to use –Match
E.g.
  •  “Crescent” –match “Honey”
  • . (dot) – one char
  • * - Zero or more match   “A” match “t*”
  • + - one or more match “TTT” match “^T+”
  • ? – Zero or one match
  • [AB] – either A or B
  • ^ - start
  • $ - end  eg. “Sala” –match “^s..A$”
  • \w – any word character  -W –Non word
  • \s – space    -S
  • \d   -D
  • (n,m) eg. “TTTT” –match “^T{4, 6}”

Strings, Arrays, Hash tables 
$H="Crescent"
$H.length
To Say “hello”: “Say “”hello”””
 

Array:  
$arr=1,2,3  or $arr=@(1,2,3)
To Get: $arr[0]
$arr2=@((1,1),(2,2),(3,3))
Get : $arr2[1][1]

Hash Table:
 
$Hash=@{No=1;CName="Crescent"}
$hash.no
$hash["Cname"]
 

XML handling: Read XML
 $MyXML=[XML] @”
<addressBook>
<Person type=“personal”>
<name>ABC</name>
<Phone>123</phone>
</person>
</addressbook>
“@
$myXML.AddressBook
$myXML.Person
$myXML.Person[0]


 
Getting Started with SharePoint PowerShell:
PowerShell contains hundreds of commands, which are called cmdlets. These application specific cmdlets usually warped to the "Snap-ins". So, to use SharePoint cmdlets in PowerShell, You need to add the SharePoint PowerShell snap-in first.

Tip: You can use "SharePoint 2013 Management Shell" which loads the SharePoint snapin into PowerShell by default!

To start with, Add PowerShell snapin to your script as the first line:
Add-PsSnapin Microsoft.SharePoint.PowerShell

Now you can use PowerShell to interact directly with SharePoint Web Applications, Site collections, Sites, Lists ,etc.

E.g. Get-SPSite -identity "http://sharepoint-site-url"

However, if you try to run your script again, you'll get an error saying:
Add-PSSnapin : Cannot add Windows PowerShell snap-in Microsoft.SharePoint.Powershell because it is already added. Verify the name of the snap-in and try again.
To mitigate use either:
if((Get-PSSnapin | Where-Object {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) 
{ 
    Add-PSSnapIn "Microsoft.SharePoint.Powershell" 
}
or
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

Introduction to PowerShell ISE:
Here are the steps to launch PowerShell ISE.
  • Go to Start >> All Programs >> Accessories >> Windows PowerShell >> Windows PowerShell ISE

 
 
Resources:
http://blogs.msdn.com/powershell
http://thepowershellguy.com
http://keithhill.spaces.live.com
http://www.leeholmes.com/blog
PowerShell Installation Instructions: http://shrinkster.com/rpy
PowerTab by MoW - http://shrinkster.com/rpx
“MSH Logo” by Lee Holmes - http://shrinkster.com/rpw
PowerShell Community Extensions: http://www.codeplex.com/PowerShellCX
MSDN - http://shrinkster.com/rpu
How to create a cmdlet: http://shrinkster.com/rpv

PowerShell Team Blog - http://blogs.msdn.com/powershell/
Lee Holmes - http://www.leeholmes.com/blog/
David Aiken - http://blogs.msdn.com/daiken/
The PowerShell Guy (MoW) - http://thepowershellguy.com/


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