Setting managed metadata fields using PnP PowerShell

A few days ago, I was trying to set some managed metadata fields in a SharePoint library using the Set-PnPListItem command – which is greatly documented.
But having worked with SharePoint for quite a few years, I immediately noticed that the examples in documentation for managed metadata fields did not contain the exception case for terms with the ‘&’ character in the label. I had to deal with this case multiple times before, so writing this blog post to hopefully save some time in the future.

If you have taxonomy terms that use the ‘&’ character, behind the scenes it gets converted to ‘&’. Notice that the character looks different, because it is a different character. You can search online for information on this as there are plenty of blog posts explaining it in detail.

To handle the special character when setting the field with Set-PnPListItem, all you have to do is replace it. Then use the new string in the Set-PnPListItem command. This also works for fields with multiple values of course.

$myString = $myString -replace '&', '&'

I have also wrote a blog post with a script to replace a specific term across all documents and folders.

But be warned…

While I was working on this, I had multiple managed metadata fields to be set on the list. To avoid repetitive string replacements in my code, I created a very simple function to do that. The function received a string and simply returned the result after the replacement – super simple. This seemed to be fine and the output on the console was correct. I could even copy/paste the value and manually run the command to set the field myself. But it din’t work within the script. When using the variable with the return of the function, it didn’t work at all!

I suspect that somehow, returning the string from the function was messing up with the characters and something was going wrong (even though console output seemed correct), but never got to the bottom of it. Maybe it’s just a known thing on how PowerShell works that I don’t know…

If you have any idea, please leave a comment below 🙂 I would really like to understand what happened

2 Replies to “Setting managed metadata fields using PnP PowerShell”

Leave a Reply

Your email address will not be published. Required fields are marked *