Search This Blog

Wednesday, November 9, 2016

Add Query Rule to SharePoint Search with Powershell for ignoring specific lists and libraries from being searched

If you are using SharePoint Search for your portal, you will observe that there may be many lists/libraries which gets searched, although you might not want the content for those libraries to be searchable. As an example, workflow history lists, custom lists containing master data.

A better way to exclude these lists is to identify the lists/libraries and add them in ignore rule for search. I have created a powershell script for the same. This can be helpful in case we want to add the rule in multiple server farms. Copy below code and paste it in file with extension - .ps1

#_____________________________Add Ignore Rule to Search_____________________________________

#Add SharePoint PowerShell SnapIn if not already added
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
       Add-PSSnapin "Microsoft.SharePoint.PowerShell"

# just append the list or library name in the variables below which you want to be ignored in search
$ListNames = ("NintexWorkflowHistory","Links","Test List")
$LibraryNames = ("Pages", "Test Library")

$CrawlPaths = ("[SITE_URL]/.*([LIBRARY_NAMES])/.*", "[SITE_URL].*/Lists/([LIST_NAMES])/.*")

# Grab the web app URL from User
write-host "Enter the Site Url:"
[string]$strSiteUrl = Read-Host



    if ($strSiteUrl -eq $null)
        Write-Host "Site URL is missing!" -foregroundcolor "magenta"

    [string]$pipe = ""

    foreach ($List in $ListNames)
        $strListNames = [string]::Concat($strListNames,$pipe,"(", $List ,")" )
        $pipe= "|"
    foreach ($Library in $LibraryNames)
         $strLibraryNames = [string]::Concat($strLibraryNames,$pipe,"(", $Library ,")" )
         $pipe= "|"


    $SearchApp = Get-SPEnterpriseSearchServiceApplication

    foreach ($CrawlPath in $CrawlPaths)
        $CrawlPath = $CrawlPath.Replace("[SITE_URL]",$strSiteUrl);
        $CrawlPath = $CrawlPath.Replace("[LIBRARY_NAMES]",$strLibraryNames);
        $CrawlPath = $CrawlPath.Replace("[LIST_NAMES]",$strListNames);
        if ((Get-SPEnterpriseSearchCrawlRule -SearchApplication $SearchApp -Identity $CrawlPath -EA SilentlyContinue))
            #Remove-SPEnterpriseSearchCrawlRule -SearchApplication $SearchApp -Identity $CrawlPath -confirm:$false
            Write-Host "Crawl Rule already exists:" + $CrawlPath -foregroundcolor "magenta"
            $Rule = New-SPEnterpriseSearchCrawlRule -SearchApplication $SearchApp -Path $CrawlPath -Type ExclusionRule -CrawlAsHttp 0 -FollowComplexUrls 0 -IsAdvancedRegularExpression 1
     Write-Host "Completed successfully..." -foregroundcolor "green"
    Write-Host  "An exception occurred. Aborting. Exception :" + $_.Exception.ToString()  -foregroundcolor "red"

Once deployed, you can view the added rule in SharePoint Search Application.

No comments:

Post a Comment