figures_carrying_house_400_clr_12497Last night I needed to reproduce really quickly a site structure we will be moving from another CMS and create a matching item hierarchy in my Sitecore instance… I could face an hour or so of boring clicking and copying and pasting and hoping I’ve not missed anything or… I could write a short PowerShell script to do the work for me… Guess which path I chose?

Before you use the script you should customize the script parameters:

  • $sitemapUrl – url of the sitemap of the site you want to clone
  • $prefix – wither site root or a branch you want to copy
  • $postfix – if a site has postfixes like .php or .aspx you want to get rid of – define it here
  • $itemTemplate – the template that should be used for items the script will create

Or just run the script and enjoy the glorious cognifide.com page structure reproduced in your Sitecore… now how cool is THAT!?

Also… now that I’ve got your attention… Cognifide’s PowerShell Console 2.0 FINAL is now available on Sitecore Marketplace. Get your copy and… Happy Scripting!

# Script configuration
# --------------------

$sitemapUrl = "http://www.cognifide.com/sitemap";

$prefix = "http://www.cognifide.com/";
$postfix = ".aspx$"

$createAt = "master:/content/Home/"
$itemTemplate = "/templates/Sample/Sample Item"

#                    
# Script starts here 
# ------------------                   

# function to create items (creates parent recursively if needed)
function CreateItem ([string]$itemName) {
  $fullPath = "$createAt\$itemName"
  $parentPath = Split-Path $itemName -parent
  if(-not (Test-Path "$createAt\$parentPath")){
    if($parentPath.Length -gt 2){
      CreateItem $parentPath
    }
  }
  if(-not (Test-Path "$fullPath")){
    "Creating $fullPath"
    $item = New-Item -ItemType $itemTemplate -Name $itemName -Path $createAt
    $item."__Display name" = $itemName -split '[\\/]' | `
      Select -last 1 | `
      ForEach-Object { $_ -replace "-", " " }
  }
}

# Get the sitemap
[xml]$w = (new-object net.webclient).DownloadString($sitemapUrl);

# Get the urls frm the xml
$locations = $w.urlset.url | `
             Where-Object {$_.loc -match $prefix} | `
             Select-Object `
               loc, `
               @{Name="Path"; `
                 Expression = {$_.loc -replace $prefix,"" -replace $postfix,""}}

# send url's for creation
$locations | % { 
  $name = $_.Path.Trim('/')
  if(-not (Test-Path "$createAt/$name")){
    CreateItem $name
  }
}


Enjoy!

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 4.00 out of 5)
Loading...



This entry (Permalink) was posted on Tuesday, July 2nd, 2013 at 3:22 am and is filed under Code Samples, Downloadable, PowerShell, Sitecore, Software, Software Development, Solution, Web applications. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response , or trackback from your own site.