Friday, 22 October 2010

Create SharePoint search keywords and best bets from a CSV file using PowerShell

If your SharePoint implementation comprises of different Search Centers across a number of site collections, managing a consistent set of keywords and best bets can be difficult through the browser UI. Each keyword can be time consuming to create, especially if it contains multiple best bets.

The script in this article allows you to use a CSV file to specify a set of keywords and best bets for a specified site collection. You can either append to any existing keywords already created in the site collection, or wipe out the current keywords and create new ones.

First, the CSV file should have the following header:

Keyword,Definition,Synonyms,BestBet1,Description1,Url1,BestBet2,Description2,Url2,BestBet3,Description3,Url3

I have specified three best bets in the example above, but you are free to add as many BestBet, Description, and Url columns as you like. Although hard to read on this page, here is an example of a CSV file with some example keywords included:

Keyword,Definition,Synonyms,BestBet1,Description1,Url1,BestBet2,Description2,Url2,BestBet3,Description3,Url3
PowerShell,Here are some links for the keyword 'PowerShell',Windows PowerShell;Scripting;PS;Scripts,Get-SPScripts,PowerShell scripts for SharePoint,
http://get-spscripts.com,Hey Scripting Guy! Blog,Microsoft TechNet blog on scripting,http://blogs.technet.com/b/heyscriptingguy/default.aspx,Effective Windows PowerShell,Free e-Book on learning PowerShell,http://keithhill.spaces.live.com/blog/cns!5A8D2641E0963A97!6930.entry
SharePoint,Here are some links for the keyword 'SharePoint',SharePoint Server;SP2010;Foundation;Collaboration,PACSharePoint.com,SharePoint blog offering hints tips and solutions,http://pacsharepoint.com,Microsoft SharePoint Team Blog,The official blog of the Microsoft SharePoint Product Group,http://blogs.msdn.com/b/sharepoint/,,,

This CSV file will add two keywords – “PowerShell” and “SharePoint” – along with synonyms and best bets for each one. Note that where there is more than one synonym for each keyword, add them as semi-colon delimited values within the CSV column.

Now the script. Before you can add the keywords, you must run the script below in PowerShell, which will set up the Import-SearchKeywords function. You will need to replace “Search Service Application” with the name of your search service application proxy from the Manage Service Applications page in Central Administration:

function Import-SearchKeywords ($SiteUrl, $CSVFilePath, [switch]$RemoveOldKeywords)
{
    $ssap = Get-SPEnterpriseSearchServiceApplicationProxy -Identity "Search Service Application"
    $keywords = New-Object Microsoft.Office.Server.Search.Administration.Keywords($ssap, $SiteUrl)
    $allKeywords = $keywords.AllKeywords
    $date = Get-Date
   
    #Remove all previous keywords from the site collection if chosen
    if($RemoveOldKeywords) {
        $keywordsArray = @()
        $allKeywords | ForEach-Object {
            $keywordsArray = $keywordsArray + $_.Term
        }
        $keywordsArray | ForEach-Object {
            write-host "Deleting keyword:"$_
            $allKeywords[$_].Delete()
        }
    }
   
    #Import CSV file
    $csvData = Import-Csv $CSVFilePath | ForEach-Object {
        #Create keyword
        write-host "Importing keyword:"$_.Keyword
        $keyword = $allKeywords.Create($_.Keyword, $date.AddHours(-1))
        $keyword.Definition = $_.Definition
       
        #Create synonyms
        $synonymArray = @()
        $synonymArray = $_.Synonyms.Split(";")
        $synonymArray | ForEach-Object {
            write-host "Creating synonym"$_ "for keyword" $keyword.Term
            if (($_ -ne $null) -and ($_ -ne "")) { $keyword.Synonyms.Create($_) }
        }
       
        #Create best bets
        $bestBetColumnNumber = 1
        $bestBetColumn = "BestBet" + $bestBetColumnNumber
        $descriptionColumn = "Description" + $bestBetColumnNumber
        $urlColumn = "Url" + $bestBetColumnNumber
       
        while ($_.$bestBetColumn) {
            write-host "Creating best bet"$_.$bestBetColumn "for keyword" $keyword.Term
            $keyword.BestBets.Create($_.$bestBetColumn, $_.$descriptionColumn, $_.$urlColumn)
           
            $bestBetColumnNumber = $bestBetColumnNumber + 1
            $bestBetColumn = "BestBet" + $bestBetColumnNumber
            $descriptionColumn = "Description" + $bestBetColumnNumber
            $urlColumn = "Url" + $bestBetColumnNumber
        }
       
        #Update keyword with best bets
        $keyword.Update()
    }
}

Once you have your CSV file ready and the script above has been run, you have one of two options for importing the keywords and best bets.

To append the keywords in your CSV with those already present in the site collection, type the following command:

Import-SearchKeywords –SiteUrl <SiteCollectionURL> –CSVFilePath <CSVFilePathAndFileName>

To delete all existing keywords from the site collection and create a new set from scratch with the contents of your CSV file, type the same command but with the RemoveOldKeywords switch:

Import-SearchKeywords –SiteUrl <SiteCollectionURL> –CSVFilePath <CSVFilePathAndFileName> -RemoveOldKeywords

For example, to create an entirely new set of keywords in the “http://portal” site collection using my example “SearchKeywords.csv” file above, you would type:

Import-SearchKeywords -SiteUrl http://portal -CSVFilePath C:\Install\SearchKeywords.csv –RemoveOldKeywords

The “Manage Keywords” site collection administration page will now look as follows:

image

And the following results will appear when I type one of my keywords in the search center:

image

If you are looking to import FAST Search keywords and user contexts to SharePoint 2010 from a CSV file, take a look at this script posted on the Microsoft TechNet Script Center at http://gallery.technet.microsoft.com/ScriptCenter/en-us/9ad93d90-9ca7-4515-b81e-441eda0390c3.

51 comments:

  1. Nice post. Well, this gave me a Heads up on what i was looking for. But what i we have multiple BestBets, i was loooking for BestBets seperated by ";" , not as "BestBet1, Description1, Url1"

    ReplyDelete
  2. Is there a way to retrieve all existing Keywords, BestBets , Synonyms and Definitions using PowerShell script from Sharepoint Enterprise Search?

    ReplyDelete
  3. You may want to read the post again - "I have specified three best bets in the example above, but you are free to add as many BestBet, Description, and Url columns as you like". Using a semi-colon delimeter wouldn't be very intuitive and adds no real benefit as far as I can tell...unless I'm missing the point.

    ReplyDelete
  4. "Is there a way to retrieve all existing Keywords, BestBets , Synonyms and Definitions using PowerShell script from Sharepoint Enterprise Search?" > You could enumerate through the site collections and send them to an XML or CSV file...but that is a whole different script than the one above...

    ReplyDelete
  5. The semicolon delimiter doesn't work. It will allow you to do it, but they won't actually work until you go into through the front end, edit the keyword and click "okay".

    For the Best Bets to work without manual intervention they need to be added one at a time (as in the example above).

    ReplyDelete
  6. Nice Post, When i was trying run the script, its asking like below
    cmdlet ForEach-Object at command pipeline position 2
    Supply values for the following parameters:
    Process[0]:

    Could you please correct me where i am doing wrong.

    Thanks
    B

    ReplyDelete
  7. Can you post a sample example of a CSV file for download?

    ReplyDelete
  8. This is great! You just saved me so much time. Thanks!

    ReplyDelete
  9. Thanks, this is terrific!

    ReplyDelete
  10. Thank you! #codehelp

    ReplyDelete
  11. Does this also work with SharePoint 2013 or are there changes that need
    to be make to the code?

    ReplyDelete
  12. Thanks for this! Our Search service crashed and I had to recreate the search application. This has happened before and with 100s of best bets it was a real chore to restore them through the UI. This saved my sanity! Nice work.

    ReplyDelete
  13. Game online a lot of people who love to help them relieve stress of the moment, such as TinyTanksandTinyPlanesorTiny Planes Beta is the fighting game with a pen or pencil, you have to destroy opponents before they kill you. Or Run 3 Unblocked and Hacked unblocked Gamesare skillful game controller for bears to dance to the goal without falling off a cliff. I wish you happy gaming!

    ReplyDelete
  14. If you have a history of illness that is difficult to recover, maybe our next article will help you to recover

    Obat untuk kencing nanah
    Obat Kudis
    Obat denam tipes
    Obat nyeri panggul
    Obat tetanus

    ReplyDelete
  15. También puede visitar una tienda de ladrillo y mortero de Michael Kors o su sitio web y comprar directamente un bolso Michael Kors desde allí. Usar un bolso de Michael Kors les permite a los demás reconocer que el habitante urbano educado toma la moda realmente con seriedad. Los bolsos de hombro son particularmente refinados y elegantes.

    {Bolsas Michael Kors Precios | Bolsos Michael Kors Outlet | Michael Kors Rebajas}

    En vacker konstnärlig skapelse av vävt läder, som ger ett skalskaligt utseende - liknar en snakeskin eller fiskhud, linjer utsidan av påsen. Läderens bältros är små läderringar. Det finns också gyllene accenter på väskan. Slutresultatet är svagt liknar kedjepost.

    {Michael Kors Rea | Michael Kors Väska Rea | Michael Kors Plånbok}

    ReplyDelete
  16. I can only express a word of thanks. Because with the content on this blog I can add knowledge I, thank has been sharing this information. Do not forget to visit our website to share information and knowledge about health.
    Cara Mengobati Keringat dingin
    Obat Keringat Dingin Herbal
    I can only express a word of thanks. Because with the content on this blog I can add knowledge I, thank has been sharing this information. Do not forget to visit our website to share information and knowledge about health.
    Obat ITP Di Apotik Untuk Anak
    Obat Herbal Penyakit Muntaber

    ReplyDelete
  17. I can only express a word of thanks. Because with the content on this blog I can add knowledge I, thank has been sharing this information. Do not forget to visit our website to share information and knowledge about health.|
    cara Mengobati Benjolan Di Kelopak mata |

    ReplyDelete
  18. I can only say thank you, for sharing information about health. Don't forget to visit our page. Thank you |
    Cara Mengatasi Penyakit Dompo khasiar hito | Cara mengobati Kesrek febri hariadi | Khasiat Propolis Brazil sule sutisna | Obat Penumbuh Daging | paling ampuh | 7 Minuman kesehatan Alami | Andre Taulani | Thank You Somuach MUachh

    ReplyDelete
  19. Subhanallah..simple analogy but deep meaning. something we know but we never realized, opened my mind and heart. Cara Mengobati Hematuria Cara Melancarkan Haid Obat Pilek Ampuh Cara Mengobati Tipes Pada Anak

    ReplyDelete
  20. I can only express a word of thanks. Because with the content on this blog I can add knowledge I, thank has been sharing this information. Do not forget to visit our website to share information and knowledge about health. |
    obat nyeri lutut akibat asam urat |
    cara menyembuhkan penyakit gudik |
    OBAT LUKA BAKAR ALAMI |
    obat kliyengan alami |
    cara menghentikan pendarahan haid

    ReplyDelete

  21. Good information. i like this srticle. This is the best blog.. Good luck..!!
    obat seklelan paling ampuh | 100% manjut dijamin original |
    benjolan di selangkangan paling ampuh |
    Obat koreng alami di apotik 100% ampuh | obat borok di kepala Terbaik.. Thank You MUach

    ReplyDelete
  22. من اهم الأشياء التي تقوم مؤسسة نقل اثاث بخميس مشيط هي الحرص القوي واطمئنان جميع عملائها الكرام تجاه الخدمة التي سوف توفرها لهم المؤسسة والأسعار التي تقوم بتقديمها المؤسسة لجميع عملائها فشركة نقل عفش بخميس مشيط تقوم بتقديم افضل العروض والتخفيضات والأسعار التي تتوافق مع الجميع وتكون مناسبة لهم فشركة نقل عفش بخميس مشيط المؤسسة الأقل في الأثمان من ضمن جميع المؤسسات الأخرى.
    شركة نقل عفش
    شركة نقل عفش من الرياض الى الامارات
    شركة نقل اثاث من الرياض الى الامارات
    شركة نقل عفش بالاحساء

    ReplyDelete
  23. Good information. i like this srticle. This is the best blog.. Good luck..!!
    Obat luka memar | paling ampuh |
    cara pesan QnC Jelly Gamat | proses cepat |
    obat bekas operasi caesar 100% Ampuh dan manjur |
    Obat Step paling ampuh | 100% manjur |
    obat benjola di pipi | 100% Alami dan ampuh obat infeksi salurran kencing | yang ampuh

    ReplyDelete
  24. Thank you for sharing a good and interesting article ...
    I hope the new posts will increase and can be a very good reference.
    Hopefully more success thank you very much..
    Cara Mengobati Kejang Demam Pada Anak
    cara mudah memesan QnC Jelly Gamat
    Obat Jantung Berdebar Dan Sesak Nafas

    ReplyDelete
  25. I can only express a word of thanks. Because with the content on this blog I can add knowledge I, thank has been sharing this information. Do not forget to visit our website to share information and knowledge about health. |
    cara mengobati tukak lambung |
    cara meyembuhkan kanker testis |
    OBAT KLIYENGAN ALAMI |
    obat kesrek di selangkangan |
    Cara Mengobati Tukak Lambung

    ReplyDelete
  26. نقل اثاث خدمة لنقل جميع أشكال الاثاث إلى أي موضع ، وذلك فتعد نقل اثاث خدمة مختصة لنقل الاثاث المخصص بالبيت ، المؤسسات ، الفنادق وغيرها من الأماكن الأخرى المتغايرة ، من المعلوم
    شركة نقل عفش

    ReplyDelete
  27. Thank you for sharing a good and interesting article ...
    I hope the new posts will increase and can be a very good reference.
    Hopefully more success thank you very much..

    cara mengobati sangkadi
    cara mengobati penyakit gudik
    obat ispa di apotik
    cara mengobati sekelan

    ReplyDelete
  28. I can only express a word of thanks. Because with the content on this blog I can add knowledge I, thank has been sharing this information. Do not forget to visit our website to share information and knowledge about health.
    obat penyakit dompo
    obat kebas dan kesemutan
    obat ispa di apotik
    cara mengobati sekelan

    ReplyDelete
  29. A beautiful purse or handbag from Coach Outlet Online can last for many years, and represent a great overall value.
    There are Michael Kors Bags Outlet in a large number of shopping malls located throughout the country.
    Cheap Michael Kors Bags is a great way to determine which models best suit your needs.
    Official Coach Factory Outlet Online all strive to provide comfort and convenience for their owners and the seams are double-stitched for maximum durability.
    Michael Kors Factory Store, has one of the most popular handbag and accessory lines on the market today.
    Coach Handbags Wholesale says a lady is classy, elegant and sophisticated.
    Coach Store Near Me trends come and go, but a Coach stands the test of time.
    The official Michael Kors Handbags On Sale Outlet regularly posts various handbags being offered for sale.
    Compare your Coach Bags On Sale Outlet to the logo provided on the website to make sure it is similar.
    All Michael Kors Outlet Online Store have serial numbers.

    ReplyDelete
  30. Niesamowita histora przytrafiła mi się. Polecam walenie kurewek z portalu z ogłoszeniami Sprawdzcie koniecznie Roksa nie wiem który link zadziala. Portalik ma dziewczyny z całej polski. zk umplem jedzimy po wszystkich miastach i po kolei ruchamy te kureweczki. Sprawdzcie jaka ekstra jazda. Dla anglików to taniocha prawie za darmo nie ma co mówić. Chłopaki wskakujcie na ten portal. Dla każdego za darmo dostęp bez kodów SMS

    ReplyDelete
  31. No matter what type of Michael Kors Bags Outlet each individual got, they all had one thing in common. We all know that getting something on sale is like winning a mini lottery, but to find a name brand handbag like Michael Kors Black Friday Sale for instance, discounted is like a slice of heaven on earth. I have personally attacked my husband with hugs and kisses when finding Official Coach Outlet Online at discounted prices.

    Michael Kors Factory Outlet stores can be found in malls all over. MK Outlet and other Coach merchandise can also be found in some boutiques. Inspired by the same material baseball gloves are made from, these Coach Bags On Sale Online are versatile and stylish. Since it's conception, the Michael Kors Handbags Outlet has been produced into a variety of designs, colors, shapes, and styles that have won top pick of millions of women the world over.

    New Michael Kors Bags are the most sought after handbag. Since Coach Outlet Online is one of the most recognized name brands in the world of fashion, you will find A-list celebrities down to small girls wearing them.

    tags:Coach Outlet|Coach Bags Factory Outlet|Coach Purses Outlet

    ReplyDelete