Wednesday, February 25, 2015

PowerShell script to get the SharePoint version


To get which version of SharePoint is installed on the server, you can use the Version property on the SPFarm object. The function below will return the version number or a 0 based on whether SharePoint is installed on the machine or not.

Function Get-SharePointVersion
{

      #Add the snapin if not present
      if((Get-PSSnapin |? {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null)
    {
        Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    }

      #Get the snapin after adding it
      $snapin = Get-PSSnapin |? {$_.Name -eq "Microsoft.SharePoint.PowerShell"}
      if($snapin -eq $null)
      {
            0
      }
      else
      {
            $snapin.Version.Major
      }
}

To test the scripts I’ve used the FluentShellUnit project and have my test cases as
[TestClass]
[DeploymentItem(@"Modules\SharePoint.psm1", "Modules")]
public class SharePointTests
{
    [TestMethod]
    [TestCategory("SharePointDSCAdministration Module")]
    public void GetSharePointVersion_should_return_versionnumber_based_on_sharepointinstallation_status()
    {
        var actual = PsFactory.Create(HostState.Core)
            .Load(@"Modules\SharePoint.psm1")
            .Execute("Get-SharePointVersion")
            .FirstResultItemAs<int>();
        Assert.IsTrue(actual == 0 || actual == 14 || actual ==15);
    }
}

No comments: