Context PowerShell scripts for Sitecore

In the he latest update of PowerShell Console for Sitecore, I?ve started experimenting with further integration ? context scripts. What is that and what can it do for you?

You can safely assume PowerShell is not something your regular users will aspire to learn, but it does not mean they cannot harness its power if you enable them to.

If you look closely at the latest Microsoft solutions you may notice that a lot of what GUI does is running some scripting behind the scenes. This is true for a long time with the SQL Server Management studio where pretty much for any action you can generate a script that will let you automate a common task.

SqlManagementScripting

Similarly but the other way around, with the PowerShell Console for Sitecore, you can attach scripts to the context menu in your item tree.

ContextScripts

Read the rest of this article »

Posted in Uncategorized
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...
| 255 Comments »

Sample scripts for Sitecore PowerShell Console

Find out about your configuration:

List your available site providers. You will use the name provided in the "Name" column in place of where I use "cms" in the later samples.

get-psdrive `
  | where-object { $_.Provider.ToString() -eq "CmsItemProvider"} `
  | format-table Name, Root

Sample scripts for working with pages:

For the same of brevity I?m assuming your location is already somewhere within a Sitecore tree (e.g. you did something akin to cd master:\content prior to executing the following scripts.

List all properties & fields available for a particular page (including Sitecore properties defined in the item template).

get-childitem | get-member -memberType property*

List all items in the CMS of which template name contains "Article"

get-childitem -recurse `
  | where-object { $_.TemplateName -match "Article" } `
  | format-table DisplayName, Name, TemplateName

List all subitems and how many days ago were they modified

get-childitem -recurse `
  | format-table -auto Name, `
  @{Label="Days since modified"; Expression={ `
  [datetime]::Now.Subtract($_.__Updated).Days} }

Delete all pages that have not been modified for the last 365 days.

get-childitem -recurse `
  | where-object {[datetime]::Now.Subtract($_.__Updated).Days -gt 365 } `
  | remove-item

List all items Updated over the last 24 hours and who changed them.

get-childitem -recurse `
  | where-object { $_.__Updated -gt [datetime]::Now.AddDays(-1) } `
  | format-table -property DisplayName, "__Updated By", {$_.Paths.Path}

List all pages that have their "Text" field filled in.

get-childitem -recurse `
  | where-object { $_.Text -ne $null } `
  | format-table -property DisplayName, {$_.Paths.Path}

Make a nice reviewer’s comment on all pages with their "Text" property filled in.

get-childitem -recurse `
  | where-object { $_.Text -ne $null } `
  | foreach-object { $_.ReviewersComment = "Great job providing content!" }

Add a warning to the beginning of "Text" property for all pages that have not been saved for the last 180 days.

get-childitem -recurse `
  | where-object {`
  [datetime]::Now.Subtract($_.__Updated).Days -ge 180 `
  -and $_.Text -ne $null }
  | foreach-object {$_.Text = "<p style='color:red'>Old content. Review pending!</p>" + $_.Text }

Replace a string in a property on all pages with another string (in this sample – removing the warning the last sample added).

$old_content = "<p style='color:red'>Old content. Review pending!</p>"
$new_content = "";
get-childitem -recurse `
  | where-object {$_.Text -match $old_content} `
  | foreach-object {$_.Text = $_.Text.Replace($old_content, $new_content) }

Display the 10 most recently changed pages ordered in the reverse chronological order or changes. Display the page name, who changed it and when as well as the page status.

get-childitem -recurse `
  | sort-object -property __Updated -descending `
  | select-object -First 10 `
  | format-table -property DisplayName, "__Updated By", __Updated

Sample scripts for working with Media Library / files:

Removes all .xml files from the ?Old Xml Files? in Media library.

cd "master:\media library\Old Xml Files"
get-childitem -recurse `
  | where-object { $_.Extension -match "xml" } `
  | remove-item

Copy all files from the "staging" folder to the "production" folder in Media Library.

Copying files within media library is done as follows. This can also be done for items in the content branch.

copy-item "master:\media library\staging\*" "master:\media library\production\"

PowerShell Console for Sitecore ? what can it do for me?

The aim of the PowerShell console for Sitecore is to create a command line interface to your data so you can automate and aggregate mundane tasks as well as create statistics and a discoverability layer on top of your content.

Have you ever found yourself:

  • having to make a mundane change to a large number of pages?
  • in need of getting statistics field or template usages?
  • being curious of e.g. what?s the oldest page on your site?
  • in need to find out how many authors really create your content and how active they are?
  • having to copy or move a large number of files from one folder to another?
  • renaming or deleting files in your file store en-masse?
  • publish pages that match some specific feature rather than a whole branch?

sharp_toolIf the answer to any of those (and more) is something akin to ?yes I did!?, I believe you might find my little plugin useful.

The idea is to create a scripting environment to work within Sitecore process, being able to make native calls to Sitecore API and modify content on a per-property level. The goal was to make it familiar to your IT and developers so they can reuse their skillset with it or if they rather learn it here, this knowledge will benefit them in the long run as clearly PowerShell is becoming an industry standard. The plugin?s aim is to manipulate not just sites, but files and pages on a large scale or perform statistical analysis of your content usingĀ  a familiar and well documented query language. The console allows you to execute and test scripts interactively, but also gives the admin means of exposing scripts to end users within context menus and in the ribbon. I?m sure in the long run I?ll come up with more applications. Scripted pipeline processors? Scripted renderings? Scripting campaigns statistics and engagement workflow steps? You name it?

Read the rest of this article »

PowerShell Console for Sitecore ? what can it do for me?

The aim of the PowerShell console for Sitecore is to create a command line interface to your data so you can automate and aggregate mundane tasks as well as create statistics and a discoverability layer on top of your content.

Have you ever found yourself:

  • having to make a mundane change to a large number of pages?
  • in need of getting statistics field or template usages?
  • being curious of e.g. what?s the oldest page on your site?
  • in need to find out how many authors really create your content and how active they are?
  • having to copy or move a large number of files from one folder to another?
  • renaming or deleting files in your file store en-masse?
  • publish pages that match some specific feature rather than a whole branch?

sharp_toolIf the answer to any of those (and more) is something akin to ?yes I did!?, I believe you might find my little plugin useful.

The idea is to create a scripting environment to work within Sitecore process, being able to make native calls to Sitecore API and modify content on a per-property level. The goal was to make it familiar to your IT and developers so they can reuse their skillset with it or if they rather learn it here, this knowledge will benefit them in the long run as clearly PowerShell is becoming an industry standard. The plugin?s aim is to manipulate not just sites, but files and pages on a large scale or perform statistical analysis of your content usingĀ  a familiar and well documented query language. The console allows you to execute and test scripts interactively, but also gives the admin means of exposing scripts to end users within context menus and in the ribbon. I?m sure in the long run I?ll come up with more applications. Scripted pipeline processors? Scripted renderings? Scripting campaigns statistics and engagement workflow steps? You name it?

Read the rest of this article »

The aim of the PowerShell console for Sitecore is to create a command line interface to your data so you can automate and aggregate mundane tasks as well as create statistics and a discoverability layer on top of your content.

Have you ever found yourself:

  • having to make a mundane change to a large number of pages?
  • in need of getting statistics field or template usages?
  • being curious of e.g. whatĆ¢Ā€Ā™s the oldest page on your site?
  • in need to find out how many authors really create your content and how active they are?
  • having to copy or move a large number of files from one folder to another?
  • renaming or deleting files in your file store en-masse?
  • publish pages that match some specific feature rather than a whole branch?

sharp_toolIf the answer to any of those (and more) is something akin to Ć¢Ā€Āœyes I did!Ć¢Ā€Ā, I believe you might find my little plugin useful.

The idea is to create a scripting environment to work within Sitecore process, being able to make native calls to Sitecore API and modify content on a per-property level. The goal was to make it familiar to your IT and developers so they can reuse their skillset with it or if they rather learn it here, this knowledge will benefit them in the long run as clearly PowerShell is becoming an industry standard. The pluginĆ¢Ā€Ā™s aim is to manipulate not just sites, but files and pages on a large scale or perform statistical analysis of your content usingƂĀ  a familiar and well documented query language. The console allows you to execute and test scripts interactively, but also gives the admin means of exposing scripts to end users within context menus and in the ribbon. IĆ¢Ā€Ā™m sure in the long run IĆ¢Ā€Ā™ll come up with more applications. Scripted pipeline processors? Scripted renderings? Scripting campaigns statistics and engagement workflow steps? You name itĆ¢Ā€Åš

Read the rest of this article »

Enable Sitecore DMS Analytics behind a proxy or a CDN

Should you put your Sitecore site behind a load balancing proxy you will run into a bit of a problem with analytics where all the Engagement Analytics app would ever report would be your own load balancing proxy’s IP address. Needless to say that is fairly big loss as you are unable to reap a host of benefits of the Sitecore CEP like page personalization, automation and reporting.

While our website was running on Sitecore 6.4 this problem was already solved and we have implemented something akin to the solution from Jeroen?s blog. Meanwhile Sitecore has reimplemented its analytics engine from the grounds up in version 6.5, and I should say they did a great job on that. However in the process the API for the analytics has changed to a degree that made our current solution obsolete, basically what we got logged looked as follows:

BrokenAnalytics

Read the rest of this article »

Posted in .Net Framework, ASP.NET, C#, Code Samples, Sitecore, Software Development, Solution
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...
| 69 Comments »

We had a situation in the company this week which required us to deliver the whole EPiServer virtual path provider file structure to the client ? zipped. Easy enough? go to the EpiServer VPP directory and? well? ok? hmm? so the path provider is versioning and as a consequence the physical organization of files on the disk does not make any sense for a human trying to browse it.

Fine! So let?s create a native provider and do a copy and paste within the file manager?. hmm an exception complaining about the provider incompatibility?

Naturally, my knee-jerk reaction is ? let?s do it with the PowerShell? which I recall was doing something like this in it?s previous version? The example I?ve tested and placed in the ?Samples? tab was:

cd VPP:\
cd \Documents\
get-childitem -recurse |
    copy-item -destination \DocumentsNonVersioningVPP\

This worked well but flattened the directory structure ? in other words useless for our client.

I?ve tried what should work in a plain PowerShell:

cd VPP:\
copy-item -path vpp:\Documents\*
          -destination vpp:\DocumentsNonVersioningVPP\
          -recurse -force

Now that didn?t work at all, and turned out to be a bug in my PowerShell plugin?s PSDrive provider. Unfortunately when I attempted to fix it by implementing the copy in the naive way ? using UnifiedDirectory?sĀ  Copy method I?ve run into the same exception about incompatibility between the classes that I?ve seen when trying to copy the files form the file manager.

Mmmkay? I?ll just implement the recursion myself? Read the rest of this article »

 

Most of this post is also based on the Microsoft?s Windows PowerShell Quick Reference however despite the sharing scripting runtimes the nature of the both shells differ considerably as described in the previous post: PowerShell for EPiServer – cheat sheet – Part 1. In all cases where it made sense I?ve converted the samples to establish them in EPiServer scenarios.

How to Write Conditional Statements

To write an If statement use code similar to this:

$page = Get-CurrentPage;
$changedBy = $page.ChangedBy;
$me = [EPiServer.Security.PrincipalInfo]::Current;
$myName = $me.Name;

if ($changedBy -eq "")
  { "Unspecified author - a system page?" }
elseif ($changedBy -eq $myName)
  { "The page has been last edited by me!" }
else
  { "The page has been last edited by "+ $changedBy }

Instead of writing a series of If statements you can use a Switch statement, which is equivalent to VBScript?s Select Case statement:

$page = Get-CurrentPage;
switch ($page.PageChildOrderRule) {
    0 {"Undefined sort order. "}
    1 {"Most recently created page will be first in list"}
    2 {"Oldest created page will be first in list"}
    3 {"Sorted alphabetical on name"}
    4 {"Sorted on page index"}
    5 {"Most recently changed page will be first in list"}
    6 {"Sort on ranking, only supported by special controls"}
    7 {"Oldest published page will be first in list"}
    8 {"Most recently published page will be first in list"}
    default {"No idea what that means!"}
  }

How to Write For and For Each Loops

Read the rest of this article »

Most of this is based on the Microsoft?s Windows PowerShell Quick Reference however despite the sharing scripting runtimes the nature of the both shells are pretty different (although the differences are not as vast as one might think).

 

Windows PowerShell PowerShell Console for EPiServer
Interactive ? command can ask for confirmations and can be aborted. User can be solicited to provide input. Batch ? all commands are being executed in one go, the script has no chance to ask questions, go or no-go decisions have to be solved within the script.
Supports colouring. Supports plain text output only.
Supports command line arguments for running scripts. All arguments are defined directly within the script or derived from context automatically.
Can access any file depending on the rights of the user. Can only access files the web application identity can write to. Cannot access files on user?s machine but rather operates on the server?s file system. Cannot operate with elevated privileges.

That said, I considered that enough of the Reference document is irrelevant in the EPiServer scenario that it?s beneficial for the users of the console to have a bespoke cheat sheet created especially for the purpose of this plugin.

The content & samples of the original cheat sheet has been adjusted to more closely reflect scenarios usable for an EPiServer admin or developer.

So here go the EPiServer specific tips

Read the rest of this article »

EPiServer Admin Mode PowerShell scripts

The PowerShell plugin gets an update once again to support Admin mode script collections in addition to the context scripts.

How to write an Admin mode script collections?

<ContextScriptCollection>
  <Title>Statistics Scripts</Title>
  <Description>This script collection ... </Description>
  <Area>Administration</Area>
  <Scripts>
    <ContextScript>
      <Title>Restart Application</Title>
      <Description>The script restarts this instance of EPiServer...</Warning>
      <Script>Restart-Application</Script>
      <Icon>/App_Themes/Default/Images/Tools/Refresh.gif</Icon>
      <Groups>
      </Groups>
    </ContextScript>
  </Scripts>
</ContextScriptCollection>

Where can I access that?

image

Read the rest of this article »