Wednesday, September 9, 2015

SharePoint PowerShell: Adding complex rules to existing audience

Here is a PowerShell script to modify an existing Audience.

As you know, in SP2010, audience rules configured from the Central Administration can only have 2 choices:
1. Meet any condition listed
2. Meet ALL conditions listed

So if I want to have more complex conditions like nested conditions, I will either need to write a program (C#) to do it, or run some powershell commands in the web front end.

DO take note that once an audience is programmatically modified, you WILL NOT BE ABLE TO MAKE CHANGES from the Central Administation console anymore.

Sample script below:



 [Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.Audience");  
 function UpdateAudience($audmanager, $name)  
 {  
  $aud = $audmanager.Audiences[$name]   
  Write-Host $aud.AudienceName -foregroundcolor "green"  
  $rules = $aud.AudienceRules # array of AudienceRuleComponent  
  # encapsulate existing rules  
  $r1pre = New-Object Microsoft.Office.Server.Audience.AudienceRuleComponent($null, "(", $null);  
  $r1post = New-Object Microsoft.Office.Server.Audience.AudienceRuleComponent($null, ")", $null);  
  $rules.Insert(0, $r1pre);  
  $rules.Add($r1post);  
  $r1 = New-Object Microsoft.Office.Server.Audience.AudienceRuleComponent($null, "AND", $null);  
  $r2 = New-Object Microsoft.Office.Server.Audience.AudienceRuleComponent($null, "(", $null);  
  $r3 = New-Object Microsoft.Office.Server.Audience.AudienceRuleComponent("Office", "Contains Contains", "Penang");  
  $r4 = New-Object Microsoft.Office.Server.Audience.AudienceRuleComponent($null, ")", $null);  
  $rules.Add($r1);  
  $rules.Add($r2);  
  $rules.Add($r3);  
  $rules.Add($r4);  
  $aud.AudienceRules = $rules;  
  $aud.Commit();  
  foreach($rule in $rules) {  
  Write-Host "$($rule.LeftContent) $($rule.Operator) $($rule.RightContent)"   
  }  
 }  
 $url = "http://sharepoint"  
 Write-Output ("Updating audiences...");  
 # Create objects  
 $spsite=new-Object Microsoft.SharePoint.SPSite($url);  
 $spcontext=[Microsoft.Office.Server.ServerContext]::GetContext($spsite);  
 $searchcontext=[Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($spsite)  
 $audmanager=New-Object Microsoft.Office.Server.Audience.AudienceManager($spcontext);  
 UpdateAudience $audmanager "Malaysian Audience"  

No comments:

Related Posts Plugin for WordPress, Blogger...