Exclude lists in search result from sites and subsites in SharePoint using PowerShell
Requirement :
Loop Through All Subsites in a Site Collection using PowerShell and exclude lists from search results (set property NoCrawl = True)
Manual approach to exclude lists from search index:
List Settings -> Advanced Settings -> set 'Allow items from this document library to appear in search results' to No
PowerShell Script to Iterate Through All Subsites in a Site Collection in SharePoint Online:
*****************************************************************************************************************************
#######################################################################################
$Username = "ABC@domain-name.com"
$Password = ConvertTo-SecureString -String "*******" -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential ($Username, $Password)
$targetWeb = "https://abc.sharepoint.com/sites/sitecollection" ## URL of the site you are uploading to
$clientid = "abc-abc-abc-abc-abc" #Add client id of site
$clientsecret = "abcdefghijklmnopq=" #Add client secret of site
$ListsNametoKeep = @("Employee","Students") #Skip list name from array where we want to keep list in search result
#########################################################################################
try {
Connect-PnPOnline -Url $targetWeb -AppId $clientid -AppSecret $clientsecret
Write-Host "Connection to site established: " $targetWeb
}
catch {
Write-Error $_
}
Get-RootSiteList
Get-SubSiteList
Function Get-RootSiteList()
{
$rootWeb=Get-PnPWeb
write-host -ForegroundColor Magenta "Getting information from the website - " $rootWeb.Title " - " $rootWeb.Url
Get-AllLists($rootWeb);
}
Function Get-AllLists($web)
{
$Lists=Get-PnPList -Web $web
try{
foreach($list in $Lists)
{
if(-not($list.Title -in $ListsNametoKeep))
{
$list.NoCrawl = $True
$list.Update()
$list.Context.ExecuteQuery()
Write-host $list.Title -ForegroundColor Yellow -NoNewline; Write-Host ' - ' -ForegroundColor Cyan -NoNewline; Write-Host ' List has been Excluded from Search Index!' -f Green
}
}
}
catch
{
write-host -f Red 'Error Excluding List ' $list.Title 'from Search Index!' $_.Exception.Message
}
}
Function Get-SubSiteList()
{
$websites=Get-PnPSubWebs -Recurse
foreach($web in $websites)
{ $Count++ #Print subsite count if required
write-host -ForegroundColor Magenta "Getting information from the website - " $web.Title " - " $web.Url
Get-AllLists($web);
}
}
*****************************************************************************************************************************
Comments
Post a Comment