Wednesday, August 10, 2022

Using Sitecore powershell for Item creation in Sitecore

 Lets try creating a sitecore item through powershell script. 

    $itemName = "new-item-name"

    $itemPath = "master:/sitecore/content/" + $itemName

    $newItem = New-Item -Path $itemPath -ItemType "template-name"

    $newItem.Editing.BeginEdit()

    $newItem["fieldname"] = "fieldvalue"

    $newItem.Editing.EndEdit()


This way of creating Sitecore items using powershell api comes in handy when we want to import Sitecore items from a static source of data i.e., a csv file or json. 

Lets see how to import sitecore item when we have the relevant records in a csv file. 

$importedData = Import-Csv -Path csv-path.csv

foreach($data in $importedData){

    $itemName = $data.Name

    $itemPath = "master:/sitecore/content/" + $itemName

    $newItem = New-Item -Path $itemPath -ItemType "template-name"

    $newItem.Editing.BeginEdit()

    $newItem["fieldname"] = $data.fieldvalue

    $newItem.Editing.EndEdit()

}

A Sample import of complete content migration. 
#Define path you want to create sitecore Items
$parentPath = "master:/sitecore/content/ctscareers/Home/ArticleListing"
#Read CSV file
$importList = Import-CSV "C:\\CSV\\SampleFileToImport.csv"
foreach($row in $importList) {
    $name = $row.Name
    #Check if Title is not empty
    if ($name.Trim() -eq "")
    {
        write-host "Item name should not be blank: " $name
        continue
    }
    $itemPath = $parentPath + "/" + $name #Create Item path
    
    $mediaitemCreated = UploadImageIntoMediaLibrary($row.ImageUrl)

    $currentItem = Get-Item -Path $itemPath -ErrorAction SilentlyContinue #Get the sitecore Item
    if ($currentItem -eq $null) #Check if Item is null then create new Item
    {
        try {
            $item = New-Item -Path $itemPath -ItemType "/sitecore/templates/Feature/CTSTraining/ArticleDetail"
            write-host "Item created: " $itemPath
        }
        catch
        {
            write-host "Failed to create Item: " $itemPath
            write-host $_.Exception.Message
            continue
        }
    }
    #Assign Field values to the Sitecore Item
    $item.Editing.BeginEdit()
    $item["PageTitle"] = $row.PageTitle
    $item["ArticleTitle"] = $row.ArticleTitle
    $item["ArticleBrief"] = $row.ArticleBrief
    $item["MetaTitle"] = $row.MetaTitle
    [Sitecore.Data.Fields.ImageField]$imageField = $item.Fields["OGImage"]
    $imageField.MediaID = $mediaitemCreated.id
    $item.Editing.EndEdit()
}

function UploadImageIntoMediaLibrary{
    [CmdletBinding()]
    param([Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
          [ValidateNotNullOrEmpty()]
          [string]$filePath)
          
    $mediaPath = "/sitecore/media library/Images"
    $mediacreatoroptions = New-Object Sitecore.Resources.Media.MediaCreatorOptions
    $mediacreatoroptions.AlternateText = "$([System.IO.Path]::GetFileNameWithoutExtension($filePath))"
    $mediacreatoroptions.Database = [Sitecore.Configuration.Factory]::GetDatabase("master");
    $mediacreatoroptions.Language = [Sitecore.Globalization.Language]::Parse("en")
    $mediacreatoroptions.Versioned = [Sitecore.Configuration.Settings+Media]::UploadAsVersionableByDefault;
    $mediacreatoroptions.Destination = "$($mediaPath)/$([System.IO.Path]::GetFileNameWithoutExtension($filePath))";
    
    $mediacreator = New-Object Sitecore.Resources.Media.MediaCreator
    $newmediaitem = $mediacreator.CreateFromFile($filePath, $mediacreatoroptions)
    return $newmediaitem
    
}