MOSS MVP

I've moved my blog to http://blog.falchionconsulting.com!. Please update your links. This blog is no longer in use--you can find all posts and comments at my new blog; I will no longer be posting to this site and comments have been disabled.

Saturday, April 25, 2009

Getting an SPFarm object using PowerShell

There are several core SharePoint objects that PowerShell programmers may need to work with in order to manipulate SharePoint via PowerShell scripts.  Getting these objects is pretty simple but not all that intuitive to users who are still trying to learn PowerShell and the SharePoint API.

The SPFarm object is the top level object for working with SharePoint and it provides access to all the global settings for all servers, services, and solutions that are installed in the farm.  To get an SPFarm object and see the public properties of that object you can either load up the Microsoft.SharePoint assembly and call the static “Local” property of the SPFarm class or use my new cmdlet, Get-SPFarm.  The first approach is shown below (note that you could of course easily move this into a function in a script and achieve the same thing as my cmdlet):

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$farm

The problem I have with the above code is that it’s just ugly so I created a real simple cmdlet that allows getting the SPFarm object with one line of code (which, again, could be achieved using a function in a script):

$farm = Get-SPFarm
$farm

Isn’t that much cleaner and easier to read:)?  The results of running the above code are shown below:

AlternateUrlCollections       : {Central Administration, SharePoint My Sites (80), SharePoint Portal (80), SharePoint Shared Services Admin (80)}
Servers                       : {SHAREPOINT1, sharepoint1.spdev.com, spsql1}
Services                      : {, , WSS_Administration, ...}
TimerService                  : SPTimerService Name=SPTimerV3 Parent=SPFarm Name=SharePoint_ConfigDB
Solutions                     : {lapointe.sharepoint.stsadm.commands.wsp}
TypeName                      : Farm
PairConnectionString          : 
IsPaired                      : False
CanMigrate                    : False
PersistedFileChunkSize        : 4194304
ErrorReportingAutomaticUpload : False
FeatureDefinitions            : {FeatureDefinition/001f4bd7-746d-403b-aa09-a6cc43de7942, FeatureDefinition/00bfea71-1c5e-4a24-b310-ba51c3eb7a57, FeatureDefinition/00bfea71-1e1d-4562-b56a-f05371bb0115, FeatureDefinition/00bfea71-2062-426c-90bf-714c59600103...}
BuildVersion                  : 12.0.0.6318
ErrorReportingEnabled         : True
DownloadErrorReportingUpdates : False
CEIPEnabled                   : False
TraceSessionGuid              : 89c8c935-99ff-48ce-9376-31daaaf32b85
ExternalBinaryStoreClassId    : 00000000-0000-0000-0000-000000000000
DiskSizeRequired              : 0
CanSelectForBackup            : True
CanRenameOnRestore            : False
CanSelectForRestore           : True
CanUpgrade                    : True
NeedsUpgradeIncludeChildren   : False
NeedsUpgrade                  : False
UpgradeContext                : Microsoft.SharePoint.Upgrade.SPUpgradeContext
Name                          : SharePoint_ConfigDB
DisplayName                   : SharePoint_ConfigDB
Id                            : 1e94781b-07f0-4f79-831e-235e0b17518c
Status                        : Online
Parent                        : SPFarm Name=SharePoint_ConfigDB
Version                       : 2279
Properties                    : {}
Farm                          : SPFarm Name=SharePoint_ConfigDB
UpgradedPersistedProperties   : {}

Obviously this is a pretty simple cmdlet and there’s not a whole of lot of advantages to doing this as a cmdlet instead of a function in a script.  The reason I went the cmdlet route for this (and the many others that I will be documenting) versus just a function is because I wanted to be able to access all my building block “stuff” in a consistent way and I wanted features such as parameter sets (which don’t make sense here but do in a lot of the others that I have).

Here’s an example script that displays all the services running on each server in the farm:

$farm = Get-SPFarm
foreach ($svr in $farm.Servers) {
    Write-Host($svr.DisplayName)
    Write-Host("-----------------------------")
    foreach ($svc in $svr.ServiceInstances) {
        Write-Host($svc.TypeName)
    }
    Write-Host("");
}

The code above produces output similar to the following:

SHAREPOINT1
-----------------------------
Session State
Windows SharePoint Services Search
Information Management Policy Configuration Service
Office SharePoint Server Search
Shared Services Timer
Office SharePoint Server Search Admin Web Service
Excel Calculation Services
Single Sign-on Service
SSP Job Control Service
Portal Service
Business Data Catalog
Office SharePoint Server Search
Document Conversions Launcher Service
Document Conversions Load Balancer Service
Windows SharePoint Services Web Application
Central Administration
Windows SharePoint Services Incoming E-Mail
Windows SharePoint Services Administration
Windows SharePoint Services Search
Windows SharePoint Services Timer
Office SharePoint Usage Analytics Service

sharepoint1.spdev.com
-----------------------------
Windows SharePoint Services Outgoing E-Mail

spsql1
-----------------------------
Windows SharePoint Services Database

The code for the cmdlet is extremely simple.  It takes no parameters and simply writes out the SPFarm.Local property:

   1: using System.Management.Automation;
   2: using Lapointe.SharePoint.PowerShell.Commands.OperationHelpers;
   3: using Microsoft.SharePoint.Administration;
   4:  
   5: namespace Lapointe.SharePoint.PowerShell.Commands.Farm
   6: {
   7:     [Cmdlet(VerbsCommon.Get, "SPFarm", SupportsShouldProcess=true)]
   8:     public class GetSPFarmCommand : PSCmdletBase
   9:     {
  10:  
  11:         /// <summary>
  12:         /// Processes the record.
  13:         /// </summary>
  14:         protected override void ProcessRecordEx()
  15:         {
  16:             WriteObject(SPFarm.Local);
  17:         }
  18:     }
  19: }

You can see the help for the Get-SPFarm cmdlet by typing “get-help get-spfarm -full”:

NAME
    Get-SPFarm
    
SYNOPSIS
    Gets an SPFarm object representing a SharePoint 2007 server farm.
    
    
SYNTAX
    Get-SPFarm [-WhatIf] [-Confirm] [<CommonParameters>]
    
    
DETAILED DESCRIPTION
    Copyright 2008 Gary Lapointe
      > For more information on these PowerShell cmdlets:
      > http://stsadm.blogspot.com/
      > Use of these cmdlets is at your own risk.
      > Gary Lapointe assumes no liability.
    

RELATED LINKS
    http://stsadm.blogspot.com

REMARKS
    For more information, type: "get-help Get-SPFarm -detailed".
    For technical information, type: "get-help Get-SPFarm -full".




NAME
    Get-SPFarm
    
SYNOPSIS
    Gets an SPFarm object representing a SharePoint 2007 server farm.
    
SYNTAX
    Get-SPFarm [-WhatIf] [-Confirm] [<CommonParameters>]
    
    
DETAILED DESCRIPTION
    Copyright 2008 Gary Lapointe
      > For more information on these PowerShell cmdlets:
      > http://stsadm.blogspot.com/
      > Use of these cmdlets is at your own risk.
      > Gary Lapointe assumes no liability.
    

PARAMETERS
    -WhatIf
        
        
        Required?                    false
        Position?                    named
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    -Confirm
        
        
        Required?                    false
        Position?                    named
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false
        
    <CommonParameters>
        This cmdlet supports the common parameters: -Verbose, -Debug,
        -ErrorAction, -ErrorVariable, and -OutVariable. For more information,
        type, "get-help about_commonparameters".
    
INPUT TYPE
    
     
    
RETURN TYPE
    SPFarm
     
    
NOTES
    
    
        For more information, type "Get-Help Get-SPFarm -detailed". For technical information, 
        type "Get-Help Get-SPFarm -full".
    
    
RELATED LINKS
    http://stsadm.blogspot.com

3 comments:

Ted Green said...

Very forward thinking, Gary. :-)

John K said...

Is this deprecated in SPS2010? There's a Get-SPFarm in microsoft.sharepoint.powershell that simply returns a guid.

Gary Lapointe said...

This cmdlet is my custom one which is only for 2007. I don't plan on updating for 2010 as there is an out of the box one that returns back an SPFarm cmdlet (it doesn't return back just a GUID - it's a full class SPFarm object).