Enable Audience targeting using script or code
Currently there are no direct methods to enable Audience Targeting on a List or Library via script or code.
This is currently done through the List or Library Settings screen under Audience targetting settings option
When you enable audience targeting through these settings, a field is created in the corresponding List or Library called Target Audiences
Get-PnpField PnP PowerShell command to get the
SchemaXml property we can see how the field is constructed.
(Get-PnPField -Identity "Target Audiences" -List Documents).SchemaXml
This is the XML returned
After some experimenting, I found that the only two columns you need to set are the
IDneeds to have 61cbb965-1e04-4273-b658-eedaa662f48d set as it’s value
Typeneeds to have TargetTo set as it’s value
You still need to provide values for
StaticName, but they can be whatever you want.
Don’t like the name Target Audiences then you can change it to something else. The great thing is, it can still be turned off through the List or Library settings page.
To enable Audinence targeting using PnP PowerShell it’s as simple as running this script.
And to do the same thing in C# CSOM
// from SharePointPnPCoreOnline Nuget package
var manager = new OfficeDevPnP.Core.AuthenticationManager();
string siteUrl = "https://contoso.sharepoint.com/sites/somesite";
string appId = "your-app-id";
string appSecret = "your-app-secret";
using (var context = manager.GetAppOnlyAuthenticatedContext(siteUrl, appId, appSecret))
var list = context.Web.Lists.GetByTitle("Documents");
var fieldSchemaXml = @"
var field = list.Fields.AddFieldAsXml(fieldSchemaXml, false, AddFieldOptions.AddFieldInternalNameHint);
To turn off Audience Targeting all you need to do is remove the field from the list.