Create Promoted Results using Powershell – Import from CSV

$siteUrl = “https://Contoso.com/search”
$resultSourceName = “Local SharePoint Results”
$web = Get-SPWeb $siteUrl
#$ssa = Get-SPEnterpriseSearchServiceApplication

$ssa = Get-SPServiceApplication -Name “Search Service”
$queryRuleManager = New-Object Microsoft.Office.Server.Search.Query.Rules.QueryRuleManager($ssa)
$site = Get-SPSite $siteUrl
$level = “SPWeb”
$searchObjectOwner = New-Object Microsoft.Office.Server.Search.Administration.SearchObjectOwner($level, $web)
$searchObjectFilter = New-Object Microsoft.Office.Server.Search.Administration.SearchObjectFilter($searchObjectOwner)
$federationManager = New-Object Microsoft.Office.Server.Search.Administration.Query.FederationManager($ssa)
$resultSource = $federationManager.GetSourceByName($resultSourceName,$searchObjectOwner)
$queryRules = $queryRuleManager.GetQueryRules($searchObjectFilter)
$promotedResultCollection = $ssa.GetBestBets($searchObjectFilter)
function CreatePromotedResult([string]$displayname , [string]$title, [string]$url,[string]$description,[string]$keywordstext)
{
try
{
Write-Host “Creating Promoted Result ..” $title
$queryRule = $queryRules.CreateQueryRule($displayname,$null,$null,$true)

[string[]]$keywords = $keywordstext.split(‘;’)

#$keywords += $title
$keywordCondition = $queryRule.QueryConditions.CreateKeywordCondition($keywords,$false)

#This is to add the below conditions
#Entire query matches exactly
#Start of query matches, but not entire query
#End of query matches, but not entire query
$queryRule.QueryConditions[0].MatchingOptions = “FullQuery,ProperPrefix,ProperSuffix”

$queryAction = $queryRule.CreateQueryAction([Microsoft.Office.Server.Search.Query.Rules.QueryActionType]::AssignBestBet)
$promotedResult = $promotedResultCollection.CreateBestBet($title, $url, $description, $false)
$queryAction.BestBetIds.Add($promotedResult.Id);
$queryRule.Update()
$queryRule = $null
Write-Host “Created Promoted Result for” $title “Finished”
}
catch
{
write-output $_.Exception.Message
}
}

function DeleteAllPromotedResult([string]$ssaName)
{
$customQueryRules = $queryRuleManager.GetQueryRules($searchObjectFilter) | ?{$_.Owner.Level -ne $ssaName}
Write-Host “There are” $customQueryRules.Count “Customised Query Rules”

foreach($qryRule in $customQueryRules) {
Write-Host “Deleting Query Rule ” $qryRule.DisplayName
$ssa.RemoveQueryRule($qryRule)
}
$ssa.Update()
}

#Delete all the Promoted Result
#DeleteAllPromotedResult($ssa)

$filepath = “D:\Temp\PowershellScripts\PR.csv”
$Rows = Import-CSV $filepath

For ($i=0;$i -lt $Rows.Count; $i++)
{
CreatePromotedResult $Rows[$i].Title $Rows[$i].DisplayName $Rows[$i].Link $Rows[$i].Description $Rows[$i].KeyWords
}

Leave a Reply

Your email address will not be published. Required fields are marked *