[BUG] AudienceIds not working after running Add-PnPNavigationNode
Reporting an Issue or Missing Feature
Issue
Expected behavior
Please let me know if this isn't the right place for this question/bug report. When I run the following code (see below) to add a Quick Launch link and add an audience it seems to work just fine. No errors are thrown and when I go to the SharePoint site I can see the audience associated with the guid was added to the link.
The problem is that the Quick Launch link is still visible to me even though I am not part of the audience. I was expecting the link to be hidden. Even more strange is that if I add the audience to the link using the UI on the SharePoint site it works as expected. The link is hidden from me.
Is there something I'm not doing correctly? All the websites I can find online say this code should work.
Almost 4 years ago someone had the same issue: https://sharepoint.stackexchange.com/questions/260831/how-to-set-navigationnode-audienceids
We cannot automate any of our sites because of this. We're forced manually rename a Quick Launch item in the SharePoint UI and click Save and then edit it again and rename it back to what it was. Why does triggering the Save in the SharePoint UI make the audiences work but not PnP?
Actual behavior
Here is a screen shot. The Audience Test 9 link should not be visible to me because I am not in that group. Even after refreshing the page it is still visible.

Steps to reproduce behavior
$newNode = Add-PnPNavigationNode -Location "QuickLaunch" -Title "Audience Test" -Url "http://linkless.header/"
$audienceList = New-Object System.Collections.Generic.List[guid]
$audienceList.add([System.guid]::New(("7e5c22f2-1254-453e-84f4-58ce4ed3e995")))
$newNode.AudienceIds = $audienceList
$newNode.Update()
Invoke-PnPQuery
What is the version of the Cmdlet module you are running?
1.11.0
Which operating system/environment are you running PnP PowerShell on?
- [X ] Windows
- [ ] Linux
- [ ] MacOS
- [ ] Azure Cloud Shell
- [ ] Azure Functions
- [ ] Other : please specify
Hi,
I'm currently experiencing the exact same problem as the author. When I update AudienceIds on a nav-node, it doesn't seem to take effect.
Once I do a "save" on the quick launch nav, then all the audience targeting are kicking in and subsequent add/remove of AudienceIds (with PnP) are taking effect.
I'm also on version 1.11.0 like OP.
Very similar code was used like OP: $n = Get-PnPNavigationNode -Id 2025 $a = New-Object System.Collections.Generic.List[guid] $a.Add([System.guid]::New(("c4771809-a3e1-4f8c-b26e-0de1ff523604"))) $n.AudienceIds = $a $n.Update() Invoke-PnPQuery
The node should be hidden to anyone not a member of "c4771809-a3e1-4f8c-b26e-0de1ff523604" but it is not and remains visible. As soon as I go into the UI and do a manual update to any node's title or url and perform a "save" (through the UI) then the node becomes hidden as the audience targeting starts to take effect. After that initial "save", any new nodes or changes to audience targeting through PnP seem to work.
So I realized there is a feature/toggle flag "Enable site navigation audience targeting" at the bottom of the quick launch edit menu. Must have something to do with this and when saving the quick launch menu edits for the first time, it probably initialized the flag/feature to true.
I tried initializing it using PnP and it still doesn't seem to work ...
When the site is first created the value of NavAudienceTargetingEnabled is "blank" or null $w = Get-PnPWeb $w.NavAudienceTargetingEnabled
This is a newly created site (also using PnP) so I figured I should try to set it with PnP using the following methods:
$w = Get-PnPWeb $w.NavAudienceTargetingEnabled = $true $w.Update() Invoke-PnPQuery
As well as:
Set-PnPWeb -NavAudienceTargetingEnabled
Both seem to have flipped the flag to True but the audience targeting settings configured using PnP were still not taking effect. PS C:> $w = Get-PnPWeb PS C:> $w.NavAudienceTargetingEnabled True
@Tran-Kien That is correct. I forgot to put it into my code snippet above but it doesn't work even if you enable audience targeting. This is the code I use for that
Connect-PnPOnline -ClientId $clientId -ClientSecret $clientSecret -Url $url
$web = Get-PnPWeb
$web.NavAudienceTargetingEnabled = $true
$web.Update()
Invoke-PnPQuery
@kbeeveer46 In case you are still looking for a work around, I had it working using PnP PowerShell cmdlet.
First, the audience targeting works after you go through the UI, modify the Quick Launch navigation and save it.
This action will trigger a REST POST call to '/_api/navigation/SaveMenuState' with a certain payload that contains the current navigation nodes and all its details (titles, urls, audiences, display order, child nodes, etc...). You can see it happen in Developper Tools (F12) / Network.
The solution revolves around doing the same REST POST call, but with the PnP cmdlet
Invoke-PnPSPRestMethod -Method Post -Url '/_api/navigation/SaveMenuState' -Content $payload
Now the challenge is building the payload to use in the call. Luckily there's another REST GET call we can do to get the current menu state which is
Invoke-PnPSPRestMethod -Method Get -Url '/_api/navigation/MenuState'
With that in mind, here's my solution to make it work:
Connect-PnPOnline
Set-PnPWeb -NavAudienceTargetingEnabled
# Add your nodes like you normally would
$newNode = Add-PnPNavigationNode -Location "QuickLaunch" -Title "Audience Test" -Url "http://linkless.header/"
$audienceList = New-Object System.Collections.Generic.List[guid]
$audienceList.add([System.guid]::New(("7e5c22f2-1254-453e-84f4-58ce4ed3e995")))
$newNode.AudienceIds = $audienceList
$newNode.Update()
Invoke-PnPQuery
# Here's the solution. This following part is what "enables" the audience targeting and makes everything take effect
$p = Invoke-PnPSPRestMethod -Method Get -Url '/_api/navigation/MenuState'
$p = @{ menuState = $p }
$payload = $p | ConvertTo-Json -Compress -Depth 7
$response = Invoke-PnPSPRestMethod -Method Post -Url '/_api/navigation/SaveMenuState' -Content $payload.ToString()
@kbeeveer46 In case you are still looking for a work around, I had it working using PnP PowerShell cmdlet.
First, the audience targeting works after you go through the UI, modify the Quick Launch navigation and save it.
This action will trigger a REST POST call to '/_api/navigation/SaveMenuState' with a certain payload that contains the current navigation nodes and all its details (titles, urls, audiences, display order, child nodes, etc...). You can see it happen in Developper Tools (F12) / Network.
The solution revolves around doing the same REST POST call, but with the PnP cmdlet
Invoke-PnPSPRestMethod -Method Post -Url '/_api/navigation/SaveMenuState' -Content $payloadNow the challenge is building the payload to use in the call. Luckily there's another REST GET call we can do to get the current menu state which is
Invoke-PnPSPRestMethod -Method Get -Url '/_api/navigation/MenuState'With that in mind, here's my solution to make it work:
Connect-PnPOnline Set-PnPWeb -NavAudienceTargetingEnabled # Add your nodes like you normally would $newNode = Add-PnPNavigationNode -Location "QuickLaunch" -Title "Audience Test" -Url "http://linkless.header/" $audienceList = New-Object System.Collections.Generic.List[guid] $audienceList.add([System.guid]::New(("7e5c22f2-1254-453e-84f4-58ce4ed3e995"))) $newNode.AudienceIds = $audienceList $newNode.Update() Invoke-PnPQuery # Here's the solution. This following part is what "enables" the audience targeting and makes everything take effect $p = Invoke-PnPSPRestMethod -Method Get -Url '/_api/navigation/MenuState' $p = @{ menuState = $p } $payload = $p | ConvertTo-Json -Compress -Depth 7 $response = Invoke-PnPSPRestMethod -Method Post -Url '/_api/navigation/SaveMenuState' -Content $payload.ToString()
@Tran-Kien That's awesome. I'll give it a try when I get some time. I also had that same idea and was trying to run any PnP command I could think of that would trigger the same action as doing it in the UI but never found one. This looks like the exact thing I was looking for.
Thanks everyone for providing these detailed analyses. I've done some digging in the SharePoint code and it looks like SaveMenuState triggers code that applies certain functionality that otherwise would not be triggered. I therefore implemented the solution of @Tran-Kien above in the Add-PnPNavigationNode cmdlet. I've also added the optional attribute -AudienceIds. So with PR #2736 applied it should work with just using:
Add-PnPNavigationNode -Location "QuickLaunch" -Title "Audience Test" -Url "https://www.bing.com" -AudienceIds 427e8f55-6d9c-461a-aad4-58863bc9a5fe
Nothing else needed.
That's great. Glad to help.
One question regarding the new parameter -AudienceIds :
In your example you are assigning only 1 AAD group GUID to the targeted audience of the new node. The new parameter -AudienceIds you introduced seems to suggest that we can assign multiple AAD group GUIDs as AudienceIds (plural). How would that work? Would we still need to build an array New-Object System.Collections.Generic.List[guid] and pass the array to the parameter?
EDIT: looking at the code of your PR, I realized the type of AudienceIds is <Guid[]> so I would guess it works the same way as we are currently used to and we can build an array of Guids and pass it to the parameter.
@KoenZomers @Tran-Kien I ran into an issue on the Invoke-PnPSPRestMethod line when I tried it
Invoke-PnPSPRestMethod : {"odata.error":{"code":"-1, Microsoft.Data.OData.ODataException","message":{"lang":"en-US","value":"An unexpected 'PrimitiveValue' node was found when reading from the JSON reader. A 'StartObject' node was expected."}}} At line:326 char:17 + ... $response = Invoke-PnPSPRestMethod -Method Post -Url '/_api/navigatio ... +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (:) [Invoke-PnPSPRestMethod], Exception + FullyQualifiedErrorId : EXCEPTION,PnP.PowerShell.Commands.Admin.InvokeSPRestMethod
Here is the contents of $payload from the line above it. It looks like valid JSON to me. The only thing that stands out to me is that "OpenInNewWindow" is null. It's the only property in each node without a value. I know that it was a new feature SharePoint rolled out recently which allows you to check a box in the UI to open the link in a new window. I wonder if it is null for you, as well, or if maybe that feature hasn't been rolled out to you and not causing you issues? I may have to edit this string in PowerShell and set its value to false and then use the updated string in the Invoke method.
{
"menuState": {
"AudienceIds": [],
"FriendlyUrlPrefix": "",
"IsAudienceTargetEnabledForGlobalNav": false,
"Nodes": [
{
"AudienceIds": [],
"CurrentLCID": 1033,
"CustomProperties": [],
"FriendlyUrlSegment": "",
"IsDeleted": false,
"IsHidden": false,
"IsTitleForExistingLanguage": false,
"Key": "2007",
"Nodes": [],
"NodeType": 0,
"OpenInNewWindow": null,
"SimpleUrl": "/sites/PTC816/SitePages/Welcome.aspx",
"Title": "Welcome",
"Translations": []
},
{
"AudienceIds": [
"49c40580-eb24-4edb-a54a-d98a706d19ed"
],
"CurrentLCID": 1033,
"CustomProperties": [],
"FriendlyUrlSegment": "",
"IsDeleted": false,
"IsHidden": false,
"IsTitleForExistingLanguage": false,
"Key": "2008",
"Nodes": [
"System.Collections.Generic.Dictionary`2[System.String,System.Object]"
],
"NodeType": 0,
"OpenInNewWindow": null,
"SimpleUrl": "http://linkless.header/",
"Title": "Motor Fuels Tax",
"Translations": []
},
{
"AudienceIds": [
"f76cee9d-d3ab-448e-bc95-c49df8fe56b0",
"3108cffb-eeb0-48ba-a52d-5d00497dd148"
],
"CurrentLCID": 1033,
"CustomProperties": [],
"FriendlyUrlSegment": "",
"IsDeleted": false,
"IsHidden": false,
"IsTitleForExistingLanguage": false,
"Key": "2010",
"Nodes": [
"System.Collections.Generic.Dictionary`2[System.String,System.Object]"
],
"NodeType": 0,
"OpenInNewWindow": null,
"SimpleUrl": "http://linkless.header/",
"Title": "Property Tax",
"Translations": []
},
{
"AudienceIds": [],
"CurrentLCID": 1033,
"CustomProperties": [],
"FriendlyUrlSegment": "",
"IsDeleted": false,
"IsHidden": false,
"IsTitleForExistingLanguage": false,
"Key": "2012",
"Nodes": [],
"NodeType": 0,
"OpenInNewWindow": null,
"SimpleUrl": "https://jira.redacted.com",
"Title": "Support",
"Translations": []
}
],
"SimpleUrl": "",
"SPSitePrefix": "/sites/PTC816",
"SPWebPrefix": "/sites/PTC816",
"StartingNodeKey": "1025",
"StartingNodeTitle": "Quick launch",
"Version": "2023-01-20T02:18:57.0396393Z"
}
}
The code that I'm using
Invoke-PnPQuery
$p = Invoke-PnPSPRestMethod -Method Get -Url '/_api/navigation/MenuState'
Write-Output $p
$p = @{menuState=$p}
Write-Output $p
$payload = $p | ConvertTo-Json -Compress -Depth 4
Write-Output $payload
$response = Invoke-PnPSPRestMethod -Method Post -Url '/_api/navigation/SaveMenuState' -Content $payload.ToString()
Write-Output $response
@kbeeveer46 your payload is wrong. The issue is because you have children nodes in your nodes "Motor Fuels Tax" and "Property Tax".
I ran into this problem as well.
To make it work: when you ConvertTo-Json give it a depth 6
$payload = $p | ConvertTo-Json -Compress -Depth 6
@Tran-Kien Thanks for the quick response! It works for me now.
We're likely going with a different implementation. PnP Core has an implementation within it now that generates the JSON based on the nodes so we don't have to do the trickery with getting it and saving it back again. Makes it a little more efficient.
@KoenZomers has fixed this issue, it will be available in tomorrow's nightly build ! Thank you for raising this :)
Hi, @KoenZomers I still have similar issue on AudienceIds when using Add-PnPNavigationNode. I've tried what you comment before, but set -Location to TopNavigationBar(the only difference), and I see nothing in AudienceIds(of the new node) field on WebUI. Do you have any good idea for this? I have a lot of sites waiting for me... I want to set this with PowerShell ::<
- PowerShell 7.2
- PnP.PowerShell 2.1.1
Thanks everyone for providing these detailed analyses. I've done some digging in the SharePoint code and it looks like SaveMenuState triggers code that applies certain functionality that otherwise would not be triggered. I therefore implemented the solution of @Tran-Kien above in the
Add-PnPNavigationNodecmdlet. I've also added the optional attribute-AudienceIds. So with PR #2736 applied it should work with just using:Add-PnPNavigationNode -Location "QuickLaunch" -Title "Audience Test" -Url "https://www.bing.com" -AudienceIds 427e8f55-6d9c-461a-aad4-58863bc9a5feNothing else needed.