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):

1[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
2$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
3$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):

1$farm = Get-SPFarm
2$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:

1$farm = Get-SPFarm
2foreach ($svr in $farm.Servers) {
3    Write-Host($svr.DisplayName)
4    Write-Host("-----------------------------")
5    foreach ($svc in $svr.ServiceInstances) {
6        Write-Host($svc.TypeName)
7    }
8    Write-Host("");
9}

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:

 1using System.Management.Automation;
 2using Lapointe.SharePoint.PowerShell.Commands.OperationHelpers;
 3using Microsoft.SharePoint.Administration;
 4 
 5namespace 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://www.falchionconsulting.com/
      > Use of these cmdlets is at your own risk.
      > Gary Lapointe assumes no liability.

RELATED LINKS
    http://www.falchionconsulting.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://www.falchionconsulting.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://www.falchionconsulting.com