Enable audience targeting in Modern site pages library using pnp PowerShell

Occasional Contributor


I am using below command to enable audience targeting on site pages library in Modern communication site. It adds a column named Target Audiences of type Audience Targeting. But I am not sure if it enables audience targeting for library since column is not visible in page properties and I do not see toggle switched to enabled in library settings.

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


Could you please help with this?


Thanks in advance.





2 Replies
If you want to target the pages for specific users, please set the permissions for those users so that they won't be able to see or access the page from the pages library. Enabling the Target Audience is fine but to edit the properties of the page, you have to add the field to the default content type of the Pages library, these are not recommended.
It is different for modern pages apparently. This worked for me:
list.Fields.AddFieldAsXml(Field1, false, AddFieldOptions.AddFieldInternalNameHint);
list.Fields.AddFieldAsXml(Field2, false, AddFieldOptions.AddFieldInternalNameHint);

public const string Field1 = "<Field ID=\"{7f759147-c861-4cd6-a11f-5aa3037d9634}\" Type=\"UserMulti\" List=\"UserInfo\" Name=\"_ModernAudienceTargetUserField\" StaticName=\"_ModernAudienceTargetUserField\" DisplayName=\"Audience\" Required=\"FALSE\" SourceID=\"{462cebd7-2503-47c2-b1f1-aa186d7b3d53}\" ShowField=\"ImnName\" ShowInDisplayForm=\"TRUE\" ShowInListSettings=\"FALSE\" UserSelectionMode=\"GroupsOnly\" UserSelectionScope=\"0\" Mult=\"TRUE\" Sortable=\"FALSE\" />";
public const string Field2 = "<Field Type=\"LookupMulti\" DisplayName=\"AudienceIds\" List=\"{37fa3000-e60f-4304-9a6f-285f7246cc83}\" FieldRef=\"7f759147-c861-4cd6-a11f-5aa3037d9634\" ReadOnly=\"TRUE\" Mult=\"TRUE\" Sortable=\"FALSE\" UnlimitedLengthInDocumentLibrary=\"FALSE\" ID=\"{80b0e0d2-6cc9-411f-891d-1aedc0a25426}\" SourceID=\"{462cebd7-2503-47c2-b1f1-aa186d7b3d53}\" StaticName=\"_ModernAudienceAadObjectIds\" Name=\"_ModernAudienceAadObjectIds\" ShowField=\"_AadObjectIdForUser\" ShowInListSettings=\"FALSE\"/>";