Get the Search Service Application for a specific site (programmatically)


October 30, 2013 - 13:46, by Steven Van de Craen - 0 Comments

I needed to get a reference to the Microsoft.Office.Server.Search.Administration.SearchServiceApplication instance for a given Microsoft.SharePoint.SPSite instance.

Here’s how you can do this in C#. I created it as an Extension Method.

public static SearchServiceApplication GetSearchServiceApplication(this SPSite site)
{
    SearchServiceApplication result = null;

    if (site != null)
    {
        SearchServiceApplicationProxy proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(site));

        if (proxy != null)
        {
            Guid ssaId = proxy.GetSearchServiceApplicationInfo().SearchServiceApplicationId;
            result = SearchService.Service.SearchApplications[ssaId] as SearchServiceApplication;
        }
    }

    return result;
}

And here’s the PowerShell counterpart. I’m no scripting guru so this might be improved here and there.

function GetSearchServiceApplication([Microsoft.SharePoint.SPSite] $site)
{
    if ($site -ne $null)
    {
        $proxy = [Microsoft.Office.Server.Search.Administration.SearchServiceApplicationProxy]::GetProxy([Microsoft.SharePoint.SPServiceContext]::GetContext($site));

        if ($proxy -ne $null)
        {
            [System.Guid] $ssaId = $proxy.GetSearchServiceApplicationInfo().SearchServiceApplicationId;
            $result = [Microsoft.Office.Server.Search.Administration.SearchService]::Service.SearchApplications | ? { $_.Id -eq $ssaId };
        }
    }

    return $result;
}

May it serve you well!