I’ve received this nice comment on one of my earlier posts and I thought it might warrant a blog post since it is a nice little challenge and might be useful for more scripters in our community.

Hi Adam,

thanks for the pointers on PowerShell! There’s one in particular I’m hoping to get some help with, if that’s ok? I have created a Branch Template in Sitecore, and I want to deploy it under every item in the Content Tree that uses one particular page template (about 200 instances of deployment, in this case). For an added bit of fun, there will be several different language versions being deployed along the way, so I guess that prevents me doing a blanket rollout. Could you please recommend a script that is along the lines of “Add this Branch Template under this Item ID in the following named language codes”? I realise I would then be repeating that line 200 times with varying parent item ID and languages, but I can live with that if that’s the easiest way to do it.

Many thanks for your help!
Phil Neale

First let’s set up a bit of a folder structure for our PoC.

#Clean-up after previous run
Remove-Item master:\content\branch-test -ErrorAction SilentlyContinue -Recurse -Force

#Create a folder strcture for our tests
New-Item master:\content\ -Name "branch-test" -ItemType "Common/Folder"

foreach($i in 1..3){

    #Create folders for items that we will serve as branch hosts
    New-Item master:\content\branch-test -Name "folder $i" -ItemType "Common/Folder" | Out-Null

    foreach($j in 1..3){

        #Create items underneath which we will be creating our branches
        New-Item "master:\content\branch-test\folder $i" -Name "branch-host $j" -ItemType "Sample/Sample Item" | Out-Null
    }
}

After this the content tree structure should look like on the following picture Read the rest of this article »

join_the_puzzle_crowd_400_clr_10889Since we’ve seen some interest from developers wanting to join the Sitecore PowerShell Extensions team, I thought it might be worth documenting how my development environment is put together to allow for easier on-boarding of new members (Yes, we’re hiring! No, we can’t pay you ;) ). Maybe you just want to compile it yourself to make sure we’re not up to no good, or just plain see inside and play with it…

First of all you need to have Sitecore installed somewhere (obviously). For the purpose of examples I’ll assume your instance is located at C:\inetpub\wwwroot\Sitecore8\ and has the 3 standard folders Data, Databases and Website in them as it normally has. For that very same reason I’ll also assume that your Sitecore PowerShell Extensions project folder is located at C:\Projects\SitecorePowerShell\

1) Seed your Sitecore instance

First step that I always perform when I setup a new environment is to seed the Sitecore instance with the items required which is best done by installing the latest release of PowerShell Extensions.

2) Set up Sitecore SPE folders to use the latest files you’re working on

Since we’re likely to modify the assets like JavaScript, styles or XML Controls I want those to be automatically synchronized with changes I do in C:\Projects\SitecorePowerShell\ for this purpose I set up junction points in my Sitecore instance folder to point at my repository folder. To do this I delete the folders that were created by the install package and perform the Junction creation. Assuming the folders as they were specified before you can write a short batch file that would look like this: Read the rest of this article »

It?s been a while since my last summary on April 2012 but finally getting to update the Reference page with the latest community summary for Sitecore PowerShell Extensions.

book_open_light_shine_out_800_clr_9090

Following are the updates I will be pushing onto the reference page I?m trying to keep up to date and failing miserably most of the time. Read the rest of this article »

Sitecore PowerShell Extensions Persistent Sessions

coach_time_out_400_clr_4749 If you?re reading this, chances are you?ve probably read about the ways of putting scripts in the Content Editor ribbon or Context Menu. Those are some simple and quick ways of extending the Sitecore UI to do quick actions accessible for your users without them having to even know about the existence of PowerShell in your system. Up until now however we?ve not been very vocal about the fact that those does not really have to be quick one-off actions but they can indeed form a broader solution to your problem through the use of persistent, named sessions. In fact Sitecore PowerShell Extensions (SPE) allow you to manage sessions and decide that it should stay in memory after the script have executed. In fact SPE does quite a bit of session maintenance itself that you might want to be aware of.

What do I really need to know about script sessions?

ScriptSession is an object that encapsulates a PowerShell Runspace. Whenever you decide to run a script 2 things will happen:

  • a ScriptSession is requested from the SessionManager (which either creates a new session or recovers an existing named session)
  • after which it?s being used to execute your script in either the current thread or a new Sitecore Job is being instantiated and the Script session is passed to it for execution.

This is decided internally based on what you?re using a Session for unless you?re instantiating it directly (like described in this post) in which case you?re responsible for disposing it.

After the script is executed and the Job has ended the session is discarded unless your script has a Persistent Session ID which I will show you how to define in just a moment.

Great so there are sessions? but what are they good for?

Read the rest of this article »

Creating reports is probably a task that every developer dread. I for once always felt like listening to Tennessee Ernie Ford?s ?16 Tons? every time when I was supposed to do it for yet another project audit ? especially this part resonated with me:

I was born one mornin’ when the sun didn’t shine
I picked up my shovel and I walked to the mine
I loaded sixteen tons of number nine coal
And the straw boss said “Well, a-bless my soul”

While the Advanced System Reporter gets you a long way, I’ve found that there were still many scenarios where I would have to write the reports by hand. Madness? Fast forward to Sitecore PowerShell Extensions (or SPE for short) it actually this doesn?t have to be like that and creating reports can be both quick and fun ? provided you?re going to use  Winking smile the module.

figure_presenting_report Read the rest of this article »

Working with Sitecore items in PowerShell Extensions

Reading some of the blogs from the Sitecore community I find it pretty apparent that we didn?t do a great job advocating the optimizations that PowerShell Extensions have introduced for working with Sitecore items. This blog attempts to rectify this problem to a degree.

group_construction_workers_400_clr_8597

How do I retrieve my Sitecore items the PowerShell way?

The most natural way to retrieve Sitecore items is with use of Get-Item and Get-ChildItem commandlets. That is because those 2 commandlets add a PowerShell wrapping around them that allows the functionalities that I?m going to describe in the next section of this blog after I?ll tell you all about retrieving items.

If you have retrieved your item directly using the Sitecore API you can still add the nice wrapper when you pipe them through the Wrap-Item commandlet as well. Some of those enhancements work in the older versions of PowerShell Extensions but I would encourage you to upgrade to the latest version (2.7 at the time this blog was written) to leverage the full potential of the environment.

Read the rest of this article »

Posted in Best Practices, Code Samples, PowerShell, Sitecore, Software Development, Solution, Web applications
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)
Loading...
| 165 Comments »

ZippingSitecoreLogsI?ve decided to 1-up the game from my previous post and zip something that isn?t really a real file but rather a blob in a Sitecore database. The script below is based heavily on the last post but instead of just zipping content of a flat folder traverses the Sitecore item tree and zips all files beneath the current folder.

If you have downloaded the 2.1 version of the Sitecore PowerShell Console from the Sitecore Marketplace you will actually have the script deployed on your system already.

Here?s how it looks like for your user in the Content Editor:

ZipAndDownloadContextMenu

The script that performs the operation looks as follows: Read the rest of this article »

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!

React to Sitecore events with PowerShell scripts

PsRocket Kieranties must be the biggest PowerShell nerd (together with yours truly) I?ve had a privilege to chat with (I guess this implies I talk to myself?). So it shouldn?t be a surprise when the two started talking PowerShell/Sitecore pixie dust started sparkling.

This time ? events integration.

What does it take to integrate PowerShell with Sitecore events?

This is a fairly easy task that Sitecore pretty thoroughly describes in the ?Using Events? SDN article. So there is little point for me to reiterate it here.

The integration requires to add some entries to the include files. I?ve added definitions for most of the item related events to the Cognifide.PowerShell.config file, but commented them out, because I don?t want you to have any performance penalty associated with the PowerShell Console installation and by default it has some scripts defined for you to try out.. All you need to do to enable it is to uncomment the <events> section of the config file and scripts will start firing up.

Implementation is pretty straightforward – the console has well defined place within its script libraries where your scripts should be placed:

Read the rest of this article »

One thing I always wanted to add to the Cognifide PowerShell Console for Sitecore but never had the chance to investigate properly, was GUI and user interaction. For example in a regular PowerShell console when an irreversible action needs to be taken or one that user needs to be notified about ? a question is asked:

image

Unfortunately due to the stateless and non-persistent nature of HTTP connections this is not easily achievable in Sitecore Sheer environment especially since in our case a PowerShell session usually lives in a separate thread within a Sitecore Job.

I knew this had to be achievable as Sitecore allows for rich interaction with user e.g. during a package installation process but I could not find any documentation regarding this subject, and my Sitecore gurus? posts were pretty discouraging in that regard:

But heck(!) Somehow the package Installer manages to show those pesky Overwrite/Merge/Skip dialogs, right?

image

Not discouraged by the early discoveries, I?ve dusted my trusty copy of Reflector and dived inside the installer code. Following are the findings of my investigations and sample solutions for using them with your Jobs.

Read the rest of this article »