Create and Remove Search Scope function
#input parameters
$siteUrl="https://td_sp_ui/SITES/TEST5"
$searchAppName="Enterprise Search Service Application"
#calling function
CCSearchScope -siteUrl $siteUrl -searchAppName $searchAppName
function CCSearchScope
{
param(
[String]$siteUrl,
[String]$searchAppName
)
#set default value for search application
if($searchAppName -eq $null -or $searchAppName -eq '')
{
$searchAppName = 'Enterprise Search Service Application'
}
#important- without / at the end
#$siteUrl = 'https://localhost/sites/newsitecollection8'
#set default value for site collection
if($SiteUrl -eq $null -or $SiteUrl -eq '')
{
$siteUrl = "https://localhost/sites/test"
}
#computed urls
$server=GetServerFromUrl $siteUrl
$site=GetSiteFromUrl $siteUrl
#scope parameters
$scopeUrl= $server + $site+"/CategoryCards/Pages"
$scopeName="category cards_fromPS"
$scopeDescription="Category Card library"
# check to ensure Microsoft.SharePoint.PowerShell is loaded
$snapin=Get-PSSnapin | Where-Object {
$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}
$searchapp = Get-SPEnterpriseSearchServiceApplication $searchAppName
$category = Get-SPEnterpriseSearchMetadataCategory –Identity SharePoint -SearchApplication $searchapp
#write-host $category
#if scope exists, delete and create new
$scope = Get-SPEnterpriseSearchQueryScope -Identity $scopeName -SearchApplication $searchapp -ea 0
if($scope -eq $null) #If scope doesn't exis, create
{
write-host $scopeName " scope doesn't exist in " $searchAppName ", creating..."
$searchapp | New-SPEnterpriseSearchQueryScope -Name $scopeName -Description $scopeDescription -DisplayInAdminUI $true
$scope = Get-SPEnterpriseSearchQueryScope -Identity $scopeName -SearchApplication $searchapp
$scopeRule = New-SPEnterpriseSearchQueryScopeRule -RuleType Url -MatchingString $scopeUrl -UrlScopeRuleType "Folder" -FilterBehavior "Include" -Url $server -Scope $scope
$scopeRule
write-host $scopeName " scope has been successfuly created in " $searchAppName "."
}
else #if scope exists, delete
{
write-host $scopeName " scope already exist in " $searchAppName ", deleting..."
Remove-SPEnterpriseSearchQueryScope -Identity $scopeName -SearchApplication $searchapp -Confirm:$false
write-host $scopeName " scope has been successfuly removed from " $searchAppName "."
}
} #end function
function GetServerFromUrl(
[string]$url
)
{
$first=$url.IndexOf('/')
$short=$url.substring($first+2,$url.length-$first-2)
$server=$url.substring(0, $short.IndexOf('/')+$first+2)
return $server
}
function GetSiteFromUrl(
[string]$url
)
{
$first=$url.IndexOf('/')
$short=$url.substring($first+2,$url.length-$first-2)
$index=$short.IndexOf('/')
$site=$short.substring($index+1, $short.length-$index-1)
return $site
}