Forum Discussion

Avian 1's avatar
Avian 1
Iron Contributor
Sep 04, 2022
Solved

Keyword Search in SharePoint 2016/Online

Hello,   I want to key word search in office document in SharePoint 2016 or SharePoint Online. I tried following code, but it is searching from all the site collections instead of site which I giv...
  • kalpeshvaghela's avatar
    kalpeshvaghela
    Sep 06, 2022

    Avian 1 

     

    Here is the updated script:

     

    $SiteURL ="https://contoso.sharepoint.com/sites/KeywordSearch1/"
    
    $keyword="(('Keyword 1') OR ('Keyword 2')) PATH:$SiteUrl"
    
    $currentTime=$(get-date).ToString("yyyyMMddHH");
    $outputFilePath="D:\Kalpesh\Scripts\results-"+$currentTime+".csv"
    
    ## Connect to SharePoint Online site
     Connect-PnPOnline -Url $SiteURL -UseWebLogin
     Write-Host "Site connected sucessfully" -ForegroundColor Green
    ## Executes an arbitrary search query against the SharePoint search
    
    
    #$results=Submit-PnPSearchQuery -Query $keyword  -All -TrimDuplicates $False // here it will export 10 items in search result
    $results = Submit-PnPSearchQuery -Query $keyword -All -TrimDuplicates:$false -SelectProperties @("Path","SPWebUrl","UrlDepth","Filename")
     
    ## Get the results in the hash table
    $hashTable=@()
    foreach($resultRow in $results.ResultRows)
    {
        $obj=New-Object PSObject
        $resultRow.GetEnumerator()| ForEach-Object{ $obj | Add-Member Noteproperty $_.Key $_.Value}
        $hashTable+=$obj;
        $obj=$null;
    }
    
    ## Export to CSV
    $hashtable | export-csv $outputFilePath -NoTypeInformation -Force
     Write-Host "Result exported sucessfully" -ForegroundColor Yellow

     

    You can use multiple key word in query like "(("Keyword 1") OR ("Keyword 2")) and so on". Reference link: https://social.msdn.microsoft.com/Forums/office/en-US/da8ffae4-e715-4a35-bdc7-5c598ac1e057/how-can-i-search-multiple-keywords-with-space-in-sharepoint-2010-?forum=sharepointdevelopmentprevious 

     

    Even if we provide SelectedProperties in command, few fixed column's value will return anyway e.g. DocId, Rank, SiteId. You can update your loop where you are preparing hash table to remove those columns from csv.

     

    Regarding Document Library path, as per my knowledge there no managed property or crawled property which can give document library path, here you need to do some string operation using UrlDepth (which is the depth of the URL i.e. split URL by "/") and SPWebUrl values.

     


    Hope it will helpful to you and if so then Please mark my response as Best Response & Like to help others in this community

     

Resources