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

Image description

When you enable audience targeting through these settings, a field is created in the corresponding List or Library called Target Audiences

Using the 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

  DisplayName="Target Audiences" 
  RowOrdinal="0" Version="2">
        <Value xmlns:q1="http://www.w3.org/2001/XMLSchema" p4:type="q1:bo
olean" xmlns:p4="http://www.w3.org/2001/XMLSchema-instance">true</Value>
        <Value xmlns:q2="http://www.w3.org/2001/XMLSchema" p4:type="q2:boolean" xmlns:p4="http://www.w
        <Value xmlns:q3="http://www.w3.org/2001/XMLSchema" p4:type="q3:boolean" xmlns:p4="http://www.w3.org/2001/XMLSchema-ins

After some experimenting, I found that the only two columns you need to set are the ID and Type

ID needs to have 61cbb965-1e04-4273-b658-eedaa662f48d set as it’s value

Type needs to have TargetTo set as it’s value

You still need to provide values for Name, DisplayName, 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.

$credentials = (Get-Credential)

Connect-PnPOnline -Url https://contoso.sharepoint.com/sites/somesite -Credentials $credentials

Add-PnPFieldFromXml '<Field ID="{61cbb965-1e04-4273-b658-eedaa662f48d}" Type="TargetTo" Name="Target_x0020_Audiences" StaticName="Target_x0020_Audiences" DisplayName="Target Audiences" />' -List Documents

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 = @"
            DisplayName='Target Audiences' 

    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.