Create Item with Specific Id Using PowerShell

Recently, I was working on Content Import in Sitecore project. Of course, I was using my most favourite tool, PowerShell for this. Ultimately I landed in a situation where few items were referring non-existent item’s id. It appeared as a broken and I was looking for options fix it.

One option was to create a new item and replace broken id with new one. Fortunately, I found an option where we can force an id for created item. The only condition is that it has to be provided while creating item, as id cant be altered after creation of item. Here is how to do it using PowerShell

New-Item -Path "master:\content\home" -Name "Demo" -ItemType "Sample/Sample Item" -ForceId "9f28cc25-5e01-4858-985e-386fcf9991b9"

That was simple. But there is a catch, it wont work when you are creating an item from Branch temple. The reason is current PowerShell implementation does not consider -ForceId parameter.

https://github.com/SitecorePowerShell/Console/blob/master/src%2FSpe%2FCore%2FProvider%2FPsSitecoreItemProvider.cs#L774

So there is no use of this parameter when creating an item with branch template.

But kudos to this article, though it is old, it’s still valid. I am copying code here to display, all credit to the original author !

function New-ItemCustom

{
<#
.SYNOPSIS
Create a new Sitecore item based on template/branch ID. Specify
the NewItemID to create the item with the specific ID.
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory=$True)]
$Name,
[Parameter(Mandatory=$True)]
[string]$TemplateID,
[Parameter(Mandatory=$True)]
$ParentItem,
[string]$NewItemID = ""
)

$scTemplateID = New-Object -TypeName "Sitecore.Data.ID" -ArgumentList $TemplateID
$newItem = $null

if ($NewItemID -ne "")
{
$scItemID = New-Object -TypeName "Sitecore.Data.ID" -ArgumentList $NewItemID
$newItem = [Sitecore.Data.Managers.ItemManager]::AddFromTemplate($Name, $scTemplateID, $ParentItem, $scItemID)
}
else
{
$newItem = [Sitecore.Data.Managers.ItemManager]::AddFromTemplate($Name, $scTemplateID, $ParentItem)
}

return $newItem
}

Just use above function in your script and use it as follows –

New-ItemCustom -Name "new item name" -TemplateID "template/branch ID" -ParentItem (Get-Item -Path: .) -NewItemID "Sitecore Item ID here"

Simple, Again !! Happy Coding !!!