Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

add/delete an event receiver to a single list with PowerShell in SharePoint 2010


In SharePoint 2010 the Event Receivers has been improved so much. But there is still a big issue on the default functionality when we want to attach/register an event receiver to a single list. By default when we create an event receiver project Visual Studio creates an Elements.xml associated to the event receiver that contains the association xml generated from the information that the Visual Studio wizard asked us. Basically, this xml associates the event receiver to a content type that we specified.
So, how should we attach an event receiver to a single list? We have two options the create a little application and do it through the object model, or using the PowerShell scripting equivalent to the object model code.
Let’s go through the second option: PowerShell
The first thing that we should do is to deploy the assembly of the Event Receiver into the GAC.
After that we can create and execute our PowerShell script.
Here It’s the sample script to register an ItemUpdated List Item Event Receiver to a single list/library:
=============================================================

$spWeb = Get-SPWeb -Identity http://moss2010
$spList = $spWeb.Lists["My List Name"]
$spEventReceiver = $spList.EventReceivers.Add()
$spEventReceiver.Assembly = "Project.Name.Class, Version=1.0.0.0, Culture=neutral, PublicKeyToken=24242342424"
$spEventReceiver.Class = "Namespace.MyClass.ClassName"
$spEventReceiver.Name = "My Event Name"
$spEventReceiver.Type = 10002
$spEventReceiver.SequenceNumber = 1000
$spEventReceiver.Synchronization = 1
$spEventReceiver.Update()
=========================================================
And some explanation of each property:
- We can get all the assembly and class information with .Net Reflector from our .dll.
- What name to put in the Name property is your choice.
- The Type property is an enumerated property whose possible values are listed in the table 1.
- The SecuenceNumber property determines the execution order of this event receiver when there are more than one event receiver attached to the same list.
- The Synchronization property is another enumerated field that could have three possible values, listed in the table 2.
Finally, we should call the Update method to persists the changes.
Well, after add our event we can check which events are attached to a list with the next PowerShell script:
======================================================

$spWeb = Get-SPWeb -Identity http://moss2010
$spList = $spWeb.Lists["My List Name"]
$spList.EventReceivers | Select Name,Assembly,Type
====================================================
This script just show us Name, Assembly and Type properties of each event attached to the list.
After that, maybe we want to delete any event receiver from a list. As you can guess… Yes! another PowerShell script can save us!:
====================================================

$spWeb = Get-SPWeb -Identity http://web.spdev.local
$spList = $spWeb.Lists["My List Name"]
$eventsCount = $spList.EventReceivers.Count
$assembly = "Project.Name.Class, Version=1.0.0.0, Culture=neutral, PublicKeyToken=24242342424"
$class = "Namespace.MyClass.ClassName"
$type = 10002
$name = "My Event Name"
for ($i = 0; $i -lt $eventsCount; $i+=1)
{
if ($spList.EventReceivers[$i].Assembly -eq $assembly -and
$spList.EventReceivers[$i].Class -eq $class -and
$spList.EventReceivers[$i].Type -eq $type -and
$spList.EventReceivers[$i].Name -eq $Name)
{
$spList.EventReceivers[$i].Delete()
}
}
$spList.Update()
=========================================================
Cool, isn’t it? In the above script we go through all the events associated to a list and delete those which Assembly, Class, Type and Name values are equal to the variables values that we set first.
As I promised here are the tables with the enumerator values.
Table 1
Member nameEnum codeDescription
InvalidReceiver -1Indicates that an invalid event receiver type has been specified.
ItemAdding 1Event that occurs before an item has been added.
ItemUpdating 2Event that occurs before an item is updated.
ItemDeleting 3An event that fires before an item is deleted.
ItemCheckingIn 4An event that occurs before an item has been checked in.
ItemCheckingOut 5An event that occurs before an item is checked out.
ItemUncheckingOut 6An event that occurs before an item is unchecked out.
ItemAttachmentAdding 7Event that occurs before an attachment has been added to an item.
ItemAttachmentDeleting 8An event that occurs before an attachment has been removed from the item.
ItemFileMoving 9An event that occurs before a file is moved.
FieldAdding 101Event that occurs before a field is added to a list.
FieldUpdating 102Event that occurs before a field is updated.
FieldDeleting 103An event that occur before a field is removed from a list.
ListAdding 104Event that occurs before a list is created.
ListDeleting 105An event that occurs before a list is deleted.
SiteDeleting 201Event that occurs before a site collection is deleted.
WebDeleting 202Event that occurs before a site is deleted.
WebMoving 203Event that occurs before site a site URL has been changed.
WebAdding 204An event that occurs before a new site is created.
WorkflowStarting 501Event that occurs before a workflow starts running.
ItemAdded 10001Event that occurs after an item has been added.
ItemUpdated 10002Event that occurs after an item has been updated.
ItemDeleted 10003An event that occurs after an item has been deleted.
ItemCheckedIn 10004Event that occurs after an item has been checked in.
ItemCheckedOut 10005An event that occurs after an item has been checked out.
ItemUncheckedOut 10006An event that occurs after an item has been unchecked out.
ItemAttachmentAdded 10007An event that occurs after an attachment has been added to the item.
ItemAttachmentDeleted 10008Event that occurs after an attachment has been removed from the item.
ItemFileMoved 10009An event that occurs after a file has been moved.
ItemFileConverted 10010An event that occurs after a file is transformed from one type to another.
FieldAdded 10101An event that occurs after a field has been added.
FieldUpdated 10102An event that occurs after a field has been updated.
FieldDeleted 10103An event that occurs after a field has been removed.
ListAdded 10104Event that occurs after a list has been created.
ListDeleted 10105Event that occurs after a list has been deleted.
SiteDeleted 10201Event that occurs after a site collection has been deleted.
WebDeleted 10202Event that occurs after a site has been deleted.
WebMoved 10203Event that occurs after a site URL has been changed.
WebProvisioned 10204An event that occurs after a new site has been created, but before that new site is provisioned.
WorkflowStarted 10501Event that occurs after a workflow has started running.
WorkflowPostponed 10502Event that occurs after a workflow has been postponed.
WorkflowCompleted 10503An event that occurs after a workflow has completed running.
EmailReceived 20000Event that occurs after a list receives an e-mail message.
ContextEvent 32766Identifies workflow event receivers, and is therefore not a true event type.
Table 2
Member nameEnum code
Default 0
Synchronous 1
Asynchronous2
Tip: If we want avoid that the event receiver is registered to any content type, we should delete the Elements.xml from the VS project.

Add a user to the SharePoint_Shell_Access role for all SharePoint 2010 content databases

In order to use Windows PowerShell for SharePoint 2010 Products, a user must be a member of the SharePoint_Shell_Access, and you can do that via Add-SPShellAdmin cmdlet. However if user needs to work with a lot of content databases then you need to repeat this procedure over and over. Here is a simple script that will add a user to the SharePoint_Shell_Access role for all content databases.

1if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
2 Add-PSSnapin Microsoft.SharePoint.PowerShell;
3}
4cls
5$username = Read-Host "Enter username";
6Get-SPContentDatabase | ForEach-Object {Add-SPShellAdmin -UserName $username -database $_.Id}





Visual Studio Pre/Post Deployment PowerShell for SharePoint

One of the projects that I'm working on at the moment involves deploying the same code base (Features, DLL etc) to a number of different site collections on my development vm. However, one of the aspects of Visual Studio 2010 it that it will only deploy to a single site - which you specify in the project settings. In this case it's a pain because certain elements of the Features require activation which only happens on that one site. If I deploy my latest code to http://site1 then everything is good, but then http://site2 and http://site3 have a mix of old and new (e.g. they'll have the latest DLL which are in the GAC but not necessarily page layouts, css etc). At the moment it means I have to go through each site and manually deactivate and then activate each Feature by hand. SharePoint deployments aren't always the quickest and this just adds extra delays which isn't very helpful.

Fortunately the deployment process through Visual Studio, especially for SharePoint projects, is extremely extensible which means you can control what happens when a deployment it done. There a couple of different out of the deployment configurations, for example Default and No Activation. Both will deploy Features to the site in the same way, except Default will also activate it. You can extend these and even write your own actions and if you install something like the CKSDev toolkit you can get some extra deployment configurations like Quick Deploy, Upgrade Solution etc which can be helpful. Another option is tying custom commands, like PowerShell which is what I'm using here.

In my case I want Visual Studio to deactivate/activate my Feature on a number of different sites, which can all be achieved through PowerShell and the standard commands that come with SharePoint. Broadly speaking I want Visual Studio to do the following:

  1. Compile, package and Deploy my Feature as normal
  2. Then loop through my sites and deactivate (if required) and activate

Everything in step 1 is done automatically by Visual Studio the only thing I'm changing is to switch the 'Active Deployment Configuration' to 'No Activation'. You don't have to, but I'd prefer having all my sites handled by the same script. So in this case, Visual Studio is only going to deploy my Feature, without activating it. For step 2 there are two parts which need changing. Firstly we have to create a PowerShell file which contains our scripts and secondly we have to amend the 'Post-deployment Command Line' which calls our custom script.

The PowerShell

For this, I just create a ps1 file at the root of my project (you can put it anywhere within the project structure). Since I only want this file to be used in Visual Studio I'm keeping the 'Copy to Output Directory' set to 'Do not copy'so it shouldn't be included in builds. This is the content of my file:

write-output "Running post-deployment scripts"

$snapin = get-pssnapin | where { $_.Name -eq "Microsoft.SharePoint.PowerShell" }

if($snapin -eq $null)

{

Add-PsSnapin Microsoft.SharePoint.PowerShell

}

$featureId = new-object System.Guid("00000000-0000-0000-0000-000000000000")

$deployableSites = "http://site1","http://site2","http://site3"

foreach($webUrl in $deployableSites)

{

$site = get-spsite $webUrl

$solution = $site.Features | where {$_.DefinitionId -eq $featureId}

if ($solution)

{

write-output "Disabling Feature for $webUrl"

disable-spfeature $featureId -url $webUrl -Confirm:$false

}

#Enable Feature

write-output "Enabling Feature for $webUrl"

enable-spfeature $featureId -url $webUrl }

The script it fairly straight-forward -

  1. Firstly we need to pull in the SharePoint PowerShell snapin
  2. Define the Feature Id and sites to deploy to 
  3. Then loop through each site, checking if it is currently available deactivate it and then activate it

You can write your script to do pretty much whatever you need it to – as long as you can write the script!

The Post-Deployment Command Line

With SharePoint we can right-click on a project, which brings up the Properties and we can head to the SharePoint tab which gives us the option to run commands both pre and post deployment. Typically this takes command line so we need to call out to PowerShell. The thing is, it's not just a case of calling out to PowerShell because of the whole 32 vs 64bit software. SharePoint as you know is 64bit, which is required for its PowerShell commands, however Visual Studio is still 32bit and so by default will call the 32bit version of PowerShell. If you try loading the SharePoint snapin in 32bit PowerShell you'll get this error:

Add-PSSnapin : The Windows PowerShell snap-in 'Microsoft.SharePoint.PowerShell' is not installed on this machine.

So instead, we need to tell Visual Studio to load the 64bit PowerShell instead which we can by referencing:

%windir%\sysnative\windowspowershell\v1.0\powershell

Now it's simply a case of passing in our deployment script we created before and deploying!

PowerShell deployment command in VIsual Studio

So the final command line is:

%windir%\sysnative\windowspowershell\v1.0\powershell -file "$(ProjectDir)PSDeploy.ps1"

Further options

This is just a simple example of how how we can incorporate PowerShell into a deployment process in Visual Studio to roll out our Features to multiple sites. Of couse the same approach can be used in Pre-deployment and also pre and post builds. So depending on when you need scripts to run you can place them where their needed.




How To Map a Crawled Property to Managed Properties By PowerShell (FAST for SharePoint 2010)

1.) Create a Managed Property from a Crawled Property

Managed Properties are great! FAST pulls and indexes Managed Properties for multitudes of things, including boosting and search scopes. They are core to your FAST User Experience and an essential part to configuration

When a FAST crawl runs, it will pick up site column data and create a crawled property for that site column (given that there is data associated with this site column). In order to query this site column directly in search, first we will created a managed property from this site column.

Generally, most out of the box SharePoint site columns are already mapped to a managed property in FAST. However, custom site columns usually are not, and these are the ones that we need to target to map to a managed property.

First we will need to make sure that our site column was indeed picked up as a crawled property. In this example, we are using a custom site column called “country”. Make sure you have already executed a crawl and that there is data associated with this site column.

From PowerShell: Executing the command Get-FASTSearchMetadataCrawledProperty in the FAST PowerShell will return the entire list of crawled properties in FAST. This can get quite verbose in your PowerShell window, so if you would like to print that out to a text file for easier viewing, execute the following simple script in PowerShell:

   1:  Get-FASTSearchMetadataCrawledProperty | Out-File “C:\crawledproperty.txt”


If you know the name of your column, you can shorten the search by adding –Name.



   1:  Get-FASTSearchMetadataCrawledProperty -Name 'country'




Basic Troubleshooting: If you get an error that the cmdlet Get-FASTSearchMetadataCrawledProperty doesn’t exist, make sure that you are FAST’s PowerShell. If the error continues, add the FAST PowerShell snap-in by typing in the command: Add-PSSnapin Microsoft.FASTSearch.Powershell



How To Map a Crawled Property to Managed Properties By PowerShell (FAST for SharePoint 2010)



From the UI: In Central Admin, go to Service Applications –> <Your FAST Query SSA> –> FAST Search Administration –> Crawled Property Categories –> SharePoint. From here you can do a search to find your site column. In general, SharePoint site columns will be preceded with “ows_”, so our returned crawled property looks like this: ows_country().



How To Map a Crawled Property to Managed Properties By PowerShell (FAST for SharePoint 2010)





Creating Managed Property



Now that we know our site column exists as a crawled property, we need to create or find a managed property to map it to. In this case, we will simply create a new managed property.



From PowerShell:



Here, ‘-type 1’ is the type of information that we are storing in the property. Make sure you make it Queryable!




# Create New Managed Property
$nmp = New-FASTSearchMetadataManagedProperty –Name “country” –type 1 –description “Managed Property for country content type”
Set-FASTSearchMetadataManagedProperty –Name “country” –Queryable $true –StemmingEnabled
$false –RefinementEnabled $false
$cp = Get-FASTSearchMetadataCrawledProperty –name 'ows_country'
New-FASTSearchMetadataCrawledPropertyMapping –Managedproperty $nmp –crawledproperty $cp







m the UI: Go to Service Applications –> <Your FAST Query SSA> –> FAST Search Administration –> Managed Properties. Click Add Managed Property. We will create a new managed property called “country”, type in a short description, and then click “Add Mapping”. This will bring up a menu where you will search for your crawled property. Once you find the managed property, add it and click ok. Finally, we will check “Query property”, which will allow you to use this managed property in search queries. There are also the options to make this managed property a sort property and deep refiner.



How To Map a Crawled Property to Managed Properties By PowerShell (FAST for SharePoint 2010)



How To Map a Crawled Property to Managed Properties By PowerShell (FAST for SharePoint 2010)



Either way we choose to create our managed property, we should be able to see it in our list of managed property names.



How To Map a Crawled Property to Managed Properties By PowerShell (FAST for SharePoint 2010)



Crawl it!



In order to use this new managed property in search and see filtered results, we must do a content crawl. Service Applications –> <Your FAST Connector> and execute an incremental or full crawl of your content source.



After your crawl, you can query directly on this column by using it as a scope in your search. For example “country:USA”.



How To Map a Crawled Property to Managed Properties By PowerShell (FAST for SharePoint 2010)

Destination Folder field in site upgraded from MOSS 2007 to SharePoint Server 2010

I am currently working on a project where we are upgrading our client’s MOSS 2007 based intranet site to SharePoint Server 2010 using the database attach upgrade method. While testing the upgraded 2010 site, we discovered that the Upload Document dialog in document libraries and Upload Picture dialog in picture libraries contained a “Destination Folder” field in addition to the “Upload Document” field. This field is only available in document libraries and picture libraries that were upgraded from the 2007 site. It is not available in document libraries or picture libraries that were newly created in the 2010 site. And this behavior was seen in the top level site and its sub-sites.

A Google search on this led me to this very informative and helpful blog by Brian McCullough. It looks like that this behavior is due to the different values that are assigned to the vti_foldersubfolderitemcount property in the Folder's property bag for an upgraded object versus a new object.

For upgraded objects, this property’s value is set to 1.

For new objects, this property’s value is set to 0.

Also, the upgrade process sets the SPWeb.CustomUploadPage property for upgraded sites to a custom upload page titled uploadex.aspx, as opposed to upload.aspx which is the default page for file uploads. And this custom upload page contains the “Destination Folder” field.

The client did not want this “Destination Folder” field in the upload dialog. Brian provided a PowerShell script in his blog that loops through all Web sites that are contained within the site collection, including the top-level site and its subsites, and checks to see if the SPWeb.CustomUploadPage property is not equal to blank. If true, then it sets the SPWeb.CustomUploadPage property to blank. Doing so, removes the custom upload page (uploadex.aspx) from SPWeb, and reverts back to the default upload page (upload.aspx), which does not contain the “Destination Folder” field.
Here is the PowerShell script to remove the custom upload page (containing the Destination Folder field):
foreach($webapp in get-spwebapplication)
{
foreach($site in $webapp.Sites)
{

foreach($web in $site.AllWebs)

{

if ($web.CustomUploadPage -ne "")

{

Out-File C:\Logs\WebsWithDestinationFolder_Log.txt -Append -InputObject $web.Url

$web.CustomUploadPage = ""

$web.Update()

}

}

}

}

How to Start a SharePoint 2010 / FS4SP Crawl Remotely

With SharePoint 2010 and FAST Search For SharePoint 2010 (FS4SP), it's easy to schedule crawls to run daily, hourly, or according to any other frequency. For most scenarios, scheduled crawls work perfectly.

Sometimes it makes more sense to kick off a crawl based on an event. For example, perhaps your organization runs an Extract/Transform/Load process to prepare data before being crawled. If that ETL job finishes at an inconsistent time, a scheduled crawl may either run too early and miss some updated data or run too late, making queries stale.

To fix that, we'd ideally kick off a new search crawl as soon as the ETL job is done running. With PowerShell, doing so is easy.

The PowerShell Script

$userName = "DOMAIN\serviceAccount"
$passWord = ConvertTo-SecureString "password" -Force -AsPlainText
$indexServerName = “serverName”

# Run the following commands on the remote computer
$credential = New-Object System.Management.Automation.PSCredential($userName, $passWord)
$session = New-PSSession $indexServerName -Authentication CredSSP -Credential $credential
Invoke-Command -Session $session -scriptBlock { `
Add-PSSnapin Microsoft.SharePoint.PowerShell; `
`
$indexServiceAppName = “Search Service Index Application”; `
`
$indexServiceApp = Get-SPServiceApplication -Name $indexServiceAppName; `
$contentSource = Get-SPEnterpriseSearchCrawlContentSource -SearchApplication $indexServiceApp `
$contentSource.StartFullCrawl() `
}

How It Works

The above script uses PowerShell remoting to issue requests on a SharePoint indexing server.

The following variables need to filled in:

  • $userName: The full username of an account with permissions to kick off a new search.
  • $passWord: The account's password. Note that dollar signs need to be escaped with tick characters in PowerShell strings (e.g. "Pa`$`$word").
  • $indexServerName: The name of a server running the index role.

An example usage is to run this script as part of a SQL job or SSIS step. The executable to call is "PowerShell.exe" with the above script saved in a "PS1" file as the command's argument.

Because SharePoint 2010 and FAST Search for SharePoint use the same service application architecture, this approach works for either system.

How to Create User Contexts, Custom User Context Properties and Site Promotions from PowerShell for SharePoint 2010

PowerShell is a powerful tool when combined with FAST. When dealing with a large site collection with multitudes of taxonomies and sites underneath it, promoting sites and keeping user contexts from environment to environment can be a long and taxing job, especially when you are working with the SharePoint/FAST UI. Luckily, this is where PowerShell comes in and saves your day.

User Context Properties

In SharePoint, you can create and edit user contexts through the UI. Under Site Settings –> FAST Search User Context, you will find all of your user contexts. The page to create a User Context looks like this out of the box:

How to Create User Contexts, Custom User Context Properties and Site Promotions from PowerShell for SharePoint 2010

Useful page, but not really right? If you want some more depth, you will have to do some digging into User Profiles. Go to Central Administration –> Service Applications –> <Your User Profile Service Application> –> Manage User Properties. Here you will find a list of user properties that are used in SharePoint, and these will be the key to making User Contexts and Site Promotions valuable and create a rich user experience for searches.

So first, let’s add a new property to the User Context. Let’s say that the User’s “Department” is an important factor in search relevancy. Therefore we want items relevant to the User’s Department to show up first in search results. To do this, we need to execute a couple PowerShell scripts.

View Current User Context Properties

First, let’s see what User Context properties are already available. If we haven’t touched them before, then we should see two of them, “SPS-Location,SPS-Responsibility”. We will be using the SharePoint PowerShell.

$properties = Get-SPEnterpriseSearchExtendedQueryProperty -SearchApplication "FASTQuery" -Identity "FASTSearchContextProperties"
$properties.Value







Where “FASTQuery” is the <Name of your FAST Query SSA>.



How to Create User Contexts, Custom User Context Properties and Site Promotions from PowerShell for SharePoint 2010



Add User Context Property



We need to make sure that we use the Name of the User Profile Property rather than the Display Name. This is especially important if we are using custom user profile properties. Also, we will need to include the old user context properties in this script, otherwise, they will be overwritten.




Set-SPEnterpriseSearchExtendedQueryProperty -SearchApplication "FASTQuery" -Identity "FASTSearchContextProperties" -Value "SPS-Location,SPS-Responsibility,Department"







Troubleshooting: Now if you go to your UI, often you won’t see any changes (the changes will be reflected in PowerShell however)! The fastest way that I’ve seen to get these changes to show is an IIS Reset. If there is a way around this, please let us know. Therefore, type in iisreset into your PowerShell, then check the UI after it has completed. It should now look like this:



How to Create User Contexts, Custom User Context Properties and Site Promotions from PowerShell for SharePoint 2010



How to Create User Contexts, Custom User Context Properties and Site Promotions from PowerShell for SharePoint 2010



Add User Contexts Using PowerShell



Now that we have some new properties to play around with, let’s add some User Contexts! In the FAST PowerShell, run the command Get-FASTSearchSearchSettingGroup. This will return the FAST Search Setting Group(s) that are on the machine. There should only be one straight out of the box. We will need the Name for the next step.



How to Create User Contexts, Custom User Context Properties and Site Promotions from PowerShell for SharePoint 2010




$searchSettingGroup = Get-FASTSearchSearchSettingGroup -Name "69d025ce-96a7-4131-adc0-7da1603e8d24"

$context = $searchSettingGroup.Contexts.AddContext("USA Marketing")

$andExpression = $context.AddAndExpression()

$orExpression = $andExpression.AddOrExpression()

$orExpression.AddMatchExpression('SPS-Location','USA')

$orExpression.AddMatchExpression('Department','Marketing')

# Optional not Expression (remove #)
# $not = andExpression.AddNotExpression()
# $not.AddMatchExpression('SPS-Location','Japan')
# $not.AddMatchExpression('SPS-Location','Canada')







This next script will add a new User Context. The true usefulness of doing this in PowerShell is the added ability to use the “not” expression to truly filter your User Context. Besides that, why is this even useful over the UI? Mainly because it’s easily portable, and you can quickly execute your PowerShell script when it’s time to move from development to production. This is handy, especially if you have multiple User Contexts, but even more so when we begin adding Site Promotions.



How to Create User Contexts, Custom User Context Properties and Site Promotions from PowerShell for SharePoint 2010



Add Site Promotions Using PowerShell



Handling site promotions and demotions can be a real hassle, especially when we begin dealing with an environment with many sites and sub-sites. Having PowerShell will make this process quick and portable from a development environment to a production environment.



Here, we begin talking about the use of “boosting” relevance and using Site Promotions. Here, we will be working with a promotion without using Keywords. This could be considered something closer to “scoping”, however the search will still extend beyond the scope of the sites included in the search. PowerShell allows you to choose your boost value automatically, assign multiple websites to your boost, and select the User Context(s) to include.



 




1:  # This PowerShell Script Adds Site Promotions for USA Marketing
3:
4: # Register the FASTSearch Powershell Snapin (if needed)
5: Add-PSSnapin Microsoft.FASTSearch.Powershell
6:
7: # Current Search Setting Group
8: $searchSettingGroup = Get-FASTSearchSearchSettingGroup -Name "69d025ce-96a7-4131-adc0-7da1603e8d24"
9:
0: # Type of Promotion
1: $globalPromotions = $searchSettingGroup.PromotionsWithoutKeyword
2:
3: # Promotion Name
4: $globalPromotion = $globalPromotions.AddPromotion("USA Marketing Sites")
5:
6: # Boost Value
7: $globalPromotion.BoostValue = 12000
8:
9:
0: ######### Begin Site Promotions Section #########
1:
2: $sitePromotionsToBeAdded = @(
3:
4: "http://intranet/USA/",
5: "http://intranet/marketing/",
6: "http://intranet/marketing/USA/",
7: "http://intranet/HR/Marketing",
8: "http://intranet/USA/Research/Marketing/",
9: "http://intranet/USA/Support/Marketing/"
0:
1: )
2:
3: # loop through site collection
4: foreach ($site in $sitePromotionsToBeAdded)
5: {
6: $uri = New-Object -Typename System.Uri -ArgumentList $site
7: $globalPromotion.PromotedItems.AddPromotedLocation($uri)
8: }
9:
0: # Add Site Promotion Individually (if needed)
1: # $uri = New-Object -TypeName System.Uri –ArgumentList http://intranet/USA
2: # $globalPromotion.PromotedItems.AddPromotedLocation($uri)
3:
4:
5: ########### End Site Promotions Section ##########
6:
7: # Added User Context
8: $userContexts = ({USA Marketing})
9: $globalPromotion.Contexts.AddContext($userContexts)







PowerShell is a clean method of adding Site Promotions to specific User Contexts in FAST Search. If you check under Site Settings –> FAST Search site promotion and demotion, you should see your new site promotion with its User Context(s) attached.



How to Create User Contexts, Custom User Context Properties and Site Promotions from PowerShell for SharePoint 2010



References:



 http://technet.microsoft.com/en-us/library/ff191225.aspx



http://blogs.technet.com/b/speschka/archive/2009/12/09/using-custom-properties-to-create-a-fast-search-for-sharepoint-2010-user-context.aspx