Working with Items
Last updated
Last updated
The majority of scripts written with SPE contain one or more of the following commands:
Use this to retrieve a single item. Throws an error if the item does not exist.
Use when Sitecore query:
or fast:
is required. May return more than 1 item.
The following commands provide you with the core methods needed to manage your content. Due to the nature of Windows PowerShell, commands such as these are extended with custom parameters and switches using Dynamic Parameters. These parameters are then added to the command at the time of use and only appear when the conditions are right. We've provided this table to help you discover the hidden gems within each command.
Legend: "–" - not applicable; "✓" - available.
Below we will show how to use each command with the Windows PowerShell syntax followed by some examples of the common C# equivalent.
If you have retrieved your items directly using the Sitecore API you can still add the nice wrapper. You can do that by piping them through the Initialize-Item
command. We'll show an example of this later.
Check out some performance details when using different methods of querying items on the Sitecore StackExchange.
Example: The following will retrieve the item based on the Sitecore path.
As you may have noticed, the /sitecore
portion of the path is unnecessary. This is because the Sitecore item is represented by the root item of the drive master:
and is therefore optional.
Let's have a look at the equivalent code in C#.
The above will return the latest version of the item in your current language. But what if you want the item in another language? No problem!
Example: The following will retrieve the Danish version of the Home item.
I've formatted the output above to show you that indeed the right language was returned. The command supports wildcards for both -Language
and -Version
parameters. You may have also noticed that the forward and backward slashes can be used interchangeably.
Example: The following retrieves the latest version for all languages of an item.
Notice that the item with language en-US
at its third version.
Example: The following retrieves the item in all languages and versions.
You can see that specifying the language and version using the wildcard will retrieve all possible variants of an item. The wildcard can also include a partial match like en-*
. The use of that filter would return all items in the English language, ignoring the region.
Example: The following retrieves the child items in all languages and versions.
It's not always most efficient to operate on items by traversing the tree using Get-ChildItem
. This is especially true if you need to work on large trees but need to select only a few items (e.g. a specific template). For this we’ve introduced support for the Sitecore query within our provider.
Important to note that the query format sometimes requires the use of a
#
before and after paths when they contain reserved keywords or spaces.Workaround found here on Sitecore Stack Exchange.
Example: The following retrieves all items beneath the path /sitecore/content/ with the template of Sample Item.
Example: The following retrieves all items beneath the path /sitecore/content/ with the template of Sample Item in all versions and languages.
Example: The following retrieves items matching the query with a specified ISO date and present in a report dialog.
Example: The following returns items with a specific template under a given root using Fast query.
The setup is not exactly like you would find in the XPath Builder but should get the job done. Read more about it here.
Example: The following retrieves items matching an XPath query.
Example: The following retrieves an item by id.
The Uri encodes the language and version within the path.
Example: The following retrieves an item by uri.
In all the examples you'll notice we specified the database. Windows PowerShell needs to know which provider to execute within. This also signals to SPE to show the dynamic parameters. Other examples of providers include the following:
HKLM: - The registry provider for HKEY_LOCAL_MACHINE.
C: - The filesystem provider for the C drive.
The following examples make use of custom PropertySet for the command Select-Object
.
Example: The following uses the PSSecurity PropertySet.
Example: The following uses the PSTemplate PropertySet.
Example: The following uses the PSImage PropertySet.
Example: The following uses the PSSchedule PropertySet.
Example: The following accesses the Image field casted to the type Sitecore.Data.Fields.ImageField
.
Note: You can use ._
and .PSFields
to gain access to the typed field.
Example: The following accesses the Link field casted to the type Sitecore.Data.Fields.LinkField
. From there you can see all of the available properties.
Example: The following finds all of the TextField
s and outputs to the console.
We often see the following two ways of accessing and changing fields used in scripts. One uses Set-ItemProperty
and the other is more natural to a Sitecore developer.
Example: The following sets the title property using Set-ItemProperty
.
Example: The following sets the title and clears the branch id using .Editing.BeginEdit
and .Editing.EndEdit
methods.
Note: The above example may also be written in the ISE where no console prompt is visible.
The previous examples work but are not the most efficient ways to change item content. The items returned by the provider expose the Sitecore item fields as automatic PowerShell properties.
If the property name on the data template contains a space, such as `Closing Date`, then you will need to wrap the field name in quotes (single or double).
Example: The following sets the title property using the automated PowerShell property.
Example: The following changes the display name of the item.
This technique may be used for a wide variety of property types.
If you need to dynamically reference a property via a property name that is stored in a variable, there are numerous ways to reference it.
Example:
There are a other hidden gems in automated PowerShell properties. For example, if we detect that the field is a Date or Datetime field, we will return System.DateTime
typed value from a field rather than the System.String
Sitecore stores internally.
Example: The following gets the created date.
Example: The following assigns a System.DateTime
value to the PowerShell automated property.
Great we've just changed it! Our property handlers take care of all the necessary usages of .Editing.BeginEdit
and .Editing.EndEdit
. This method can be applied for a variety of field types such as GeneralLink and Image.
To provide an example – I’ve extended my home with additional fields as follows:
Example: The following assigns an image to the Image field.
Easy enough, isn't it? Let SPE detect the field type for you and worry about what to call! Now let's assign a content item to GeneralLink.
Example: The following assigns a content item to a GeneralLink field.
What about fields that accept lists of items? We've got your back here as well.
Example: The following assigns all children of /sitecore/content/
item to the ItemList field.
Let's see how our item looks in the Content editor after all the assignments that we've just performed:
Great! Looks like it worked.
Those little improvements make your scripts much more succinct and understandable. Try it for yourself!
As with every rule there is an exception to this one. Those automated properties perform the $item.Editing.BeginEdit()
and $item.Editing.EndEdit()
every time which results in saving the item after every assignment. Assigning multiple properties on an item this way might be detrimental to the performance of your script. In such cases you might want to call $item.Editing.BeginEdit()
yourself before modifying the item. Subsequently call the $item["field name"] = "new value"
for each property modify. Finally end with the $item.Editing.EndEdit()
.
Choosing this way is situational and will usually only be required if you're working with a large volume of data. In those cases you might also want to introduce the Sitecore.Data.BulkUpdateContext
technique.
Example: The following sets multiple properties while using the Sitecore.Data.BulkUpdateContext
.
Example: The following generates a relative url to the specified site and assigns to a variable. Because the New-UsingBlock
command creates a new closure, you need to return the data to use in a different scope.
Some other classes you may want to use with the New-UsingBlock
function:
Sitecore.SecurityModel.SecurityDisabler
Sitecore.Data.BulkUpdateContext
Sitecore.Globalization.LanguageSwitcher
Sitecore.Sites.SiteContextSwitcher
Sitecore.Data.DatabaseSwitcher
Sitecore.Security.Accounts.UserSwitcher
Sitecore.Data.Items.EditContext
Sitecore.Data.Proxies.ProxyDisabler
Sitecore.Data.DatabaseCacheDisabler
Sitecore.Data.Events.EventDisabler
If you have reached this point, then you are clearly a nerd and want to access using the raw Sitecore API.
Example: The following queries all descendants of the media library, filters by size, and wraps with automatic properties.
You will find yourself one day in need of copying items on a small to large scale. The Copy-Item
command will likely meet the need.
Example: The following copies the item to the specified path with a new ID.
Note: The item name will match just as you type it in the command. Lowercase name in the destination will result in an item with a lowercase name.
Example: The following transfers the item to the specified path with the same ID.
Example: The following copies an entire tree of items and maintains the tree structure.
There is a always a better way to do something. Moving items en masse is certainly one that you don't want to do by hand. If the destination item exists the moved item will be added as a child. If the destination item does not exist the source item will be renamed when moved.
Example: The following moves the item from one parent to another.
Example: The following gets an item and moves to a new parent node, along with all the children.
Example: The following creates a new item with the specified template.
Example: The following creates a new item with the specified template id and id.
Example: The following creates a new item as a child of the specified item.
Note: The New-Item
command was passed to Format-Table -Autosize
to improve the formatting.
Example: The following removes the item permanently. Proceed with caution.
Parameter Name
Description
Copy-Item
Get-Item
Get-ChildItem
Move-Item
New-Item
Remove-Item
AmbiguousPaths
More than one item matches the criteria so show them all.
–
✓
-
–
–
–
Database
The specified database will be used. Requires the ID to be set.
–
✓
–
–
–
–
DestinationItem
Parent item to receive the copied item.
✓
–
–
✓
–
–
FailSilently
Unauthorized access errors will be suppressed
✓
–
–
✓
–
✓
ForceId
Forces the new item to use a specified GUID
–
–
–
–
✓
–
ID
Matches the item by ID.
–
✓
✓
–
–
–
Item
Instance item.
✓
–
✓
✓
–
✓
Language
Specifies the languages to include.
–
✓
✓
–
✓
–
Parent
Specifies the parent item.
–
–
–
–
✓
–
Permanently
Specifies the item should be deleted rather than recycled.
–
–
–
–
–
✓
Query
Matches the items by an XPath query.
–
✓
–
–
–
–
StartWorkflow
Initiates the default workflow, if any.
–
–
–
–
✓
–
TransferOptions
Options flag used when copying from one database to another.
✓
–
–
✓
–
–
Uri
Matches the item by ItemUri.
–
✓
–
–
–
–
Version
Specifies the version to include.
–
✓
✓
–
–
–
WithParent
Specifies the command should include the parent item.
–
-
✓
–
–
–