Skip to main content

Microsoft

Sitecore Powershell – Update field values

The Powershell module for Sitecore is quickly becoming one of my new favorite Sitecore tools. I’m still learning the Sitecore Powershell ropes and with the help of various blog posts, including the series started by Jon Upchurch, I’m slowly getting better with it.
This week a project required an update to certain links that were contained in Rich Text fields. My first instinct was to use Powershell, instead of in the past it would’ve been a C# method kicked off by a service call, so that’s a step in the right direction.
It took some trial and error, some Googling, and some assistance from SitecoreJon to get the things going. The end result works, but I’m sure there are probably smoother ways to accomplish the same goal. Since this was a one-off script that would only need to be run once, I didn’t worry as much about performance. This is also where I thought posting it would trigger responses from Powershell experts for various alternatives to help me learn the right way to do this in the future and the ‘why’ behind it.
Use case: Locate all rich text fields, regardless of their name and if a certain value exists, replace it with another value. In this case, it’s the href value of an <a tag.
Script:
 

$root = gi master:// -id "{0C3015B8-77AD-44DC-9633-2AD76489483A}"
$items = $root | ls -r | %{$item = $_; $_.Fields  | ?{$_.TypeKey -eq "rich text"} }
#$items.Count
foreach($i in $items){
    if($temp){
        clear-variable("temp")
    }
    if($replaced){
        clear-variable("replaced")
    }
    $replaced = $i.Value -replace 'https://randomlink.com', 'https://newlink.com'
    $temp = $i.Item
    $temp.Editing.BeginEdit()
    $temp.Fields[$i.Name].Value = $replaced
    $temp.Editing.EndEdit()
}

In the above script I’m using the Sitecore API for the editing portions because it was more intuitive to me.
The statement

$items = $root | ls -r | %{$item = $_; $_.Fields  | ?{$_.TypeKey -eq "rich text"} }

retrieves all of the fields underneath the context item that are Rich Text fields.
The fields themselves do not have the Editing member and I ran into a bunch of null reference errors, so I retrieved the field’s ‘.Item’ property. To check the item’s members I used the ‘gm’ cmdlet on a single item to see what was exposed. Once I get to that place I was in more familiar territory because editing items in C# is done the same way using the Sitecore API.
That all being said, how would you handle this use case? Please feel free to comment on this with suggestions or any other opinions on the process.
Thanks!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

William Cacy

More from this Author

Categories
Follow Us
TwitterLinkedinFacebookYoutubeInstagram