<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Codality</title>
	<atom:link href="http://blog.najmanowicz.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.najmanowicz.com</link>
	<description>Code and Effect - solving problem with just enough amount of code - by Adam Najmanowicz</description>
	<lastBuildDate>Fri, 20 Apr 2012 09:39:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Using PowerShell Console for Sitecore in your own code</title>
		<link>http://blog.najmanowicz.com/2012/04/06/using-powershell-console-for-sitecore-in-your-own-code/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-powershell-console-for-sitecore-in-your-own-code</link>
		<comments>http://blog.najmanowicz.com/2012/04/06/using-powershell-console-for-sitecore-in-your-own-code/#comments</comments>
		<pubDate>Fri, 06 Apr 2012 13:22:56 +0000</pubDate>
		<dc:creator>Adam Najmanowicz</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Sitecore]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Web applications]]></category>

		<guid isPermaLink="false">http://blog.najmanowicz.com/?p=560</guid>
		<description><![CDATA[With the latest update of PowerShell Console For Sitecore can run the PowerShell environment in your application and take advantage of its scripting power, by getting the results out of it and pulling them into your app.]]></description>
			<content:encoded><![CDATA[<p>All of the PowerShell blog posts so far were about using the console. Being the developer however, you probably think – well that&#8217;s good for admins, but what’s in it for me? How can I benefit from it in my code? Well you can. With the latest update you can run the PowerShell environment in your application and take advantage of its scripting power, by getting the results out of it and pulling them into your app.</p>
<p><a href="http://blog.najmanowicz.com/wp-content/uploads/2012/04/PowerShellPlug.png" rel="lightbox[560]" title="PowerShellPlug"><img style="background-image: none; float: none; padding-top: 0px; padding-left: 0px; margin: 4px auto; display: block; padding-right: 0px; border-width: 0px;" title="PowerShellPlug" src="http://blog.najmanowicz.com/wp-content/uploads/2012/04/PowerShellPlug_thumb.png" alt="PowerShellPlug" width="300" height="162" border="0" /></a></p>
<h3>So How do I tap into the PowerShell goodness?</h3>
<p><span id="more-560"></span><br />
First of all, you download the PowerShell Console from its <a href="http://trac.sitecore.net/SitecorePowershellConsole/">Sitecore Shared Source site</a>. Reference the <span style="font-family: 'Courier New';">Cognifide.PowerShell.dll</span> from your application and add the following to your class:</p>
<p>using Cognifide.PowerShell.Shell.Host;</p>
<p>Now you can run your PowerShell script by using code that looks like follows:</p>
<pre class="brush: csharp; title: ; notranslate">
using (ScriptSession session = new ScriptSession())
{
    // sample script that returns processes
    var scriptResults = session.ExecuteScriptPart(
      &quot;get-process | where-object { $_.ProcessName -eq 'w3wp' }&quot;,
      false);

    //iterate through the results to retrieve the
    foreach (Process process in scriptResults)
    {
        WebProcesses = WebProcesses + process.SessionId + &quot;,&quot;;
    }
}
</pre>
<p>In the above sample the environment is used to pull all w3wp processes and create a coma separated list of their ID&#8217;s. While you may not find this sample very compelling, just think what you have the whole PowerShell filtering and processing engine at your disposal, that’s including the ability to traverse Sitecore tree and perform actions and creating the script dynamically in your code. You could think of it like a Regexp, but for your environment rather than for Strings.</p>
<p>If you want to get the results PowerShell would print out rather than the objects themselves, you can put &#8220;<span style="font-family: 'Courier New';">true</span>” in the second parameter of <span style="font-family: 'Courier New';">ExecuteScriptPart</span> and then iterate over the Output property of the session to access the results.</p>
<pre class="brush: csharp; title: ; notranslate">
using (ScriptSession session = new ScriptSession())
{
    // sample script that lists w3wp processes list
    session.ExecuteScriptPart(
      &quot;get-process | where-object { $_.ProcessName -eq 'w3wp' }&quot;,
      true);

    //iterate through the output lines to display them
    foreach (var output in session.Output)
    {
        WebProcesses = WebProcesses + output.Text + &quot;&lt;/br&gt;&quot;;
    }
}
</pre>
<p>Naturally you can do something at this level without the PowerShell Console for Sitecore (<a href="http://code.msdn.microsoft.com/windowsdesktop/CSPowerShell-1f44f80d">and here’s how</a>). What the console gives you is the access to all the Sitecore specific elements like being able to access items like drives e.g. “cd master:\content\home\” etc as well as all of the custom commandlets.</p>
<p>To get access to the above functionality you need the console in version 2.0 beta5 or later.</p>
<img src="http://blog.najmanowicz.com/?ak_action=api_record_view&id=560&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://blog.najmanowicz.com/2012/04/06/using-powershell-console-for-sitecore-in-your-own-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Your own PowerShell commandlets</title>
		<link>http://blog.najmanowicz.com/2012/04/03/your-own-powershell-commandlets/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=your-own-powershell-commandlets</link>
		<comments>http://blog.najmanowicz.com/2012/04/03/your-own-powershell-commandlets/#comments</comments>
		<pubDate>Tue, 03 Apr 2012 10:38:44 +0000</pubDate>
		<dc:creator>Adam Najmanowicz</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Sitecore]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Solution]]></category>
		<category><![CDATA[Web applications]]></category>

		<guid isPermaLink="false">http://blog.najmanowicz.com/?p=537</guid>
		<description><![CDATA[There is a lot of new stuff in the imminent 2.0 release of the PowerShell Console for Sitecore. Some of it is fairly obvious like the improved console window, some of it not so much. The aim of the console has always be to enable Sitecore developers to extend the CMS in new exciting ways. [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.najmanowicz.com/wp-content/uploads/2012/04/swiss-choc.jpg" rel="lightbox[537]" title="swiss-choc"><img style="background-image: none; float: right; padding-top: 0px; padding-left: 0px; margin: 12px 12px 0px 30px; display: inline; padding-right: 0px; border: 0px;" title="swiss-choc" src="http://blog.najmanowicz.com/wp-content/uploads/2012/04/swiss-choc_thumb.jpg" alt="swiss-choc" width="240" height="276" align="right" border="0" /></a>There is a lot of new stuff in the imminent 2.0 release of the PowerShell Console for Sitecore. Some of it is fairly obvious like the improved console window, some of it not so much. The aim of the console has always be to enable Sitecore developers to extend the CMS in new exciting ways. For this to happen it had to become a mini-platform on its own. So far you could use it to add scripts to <a href="http://blog.najmanowicz.com/2011/11/24/extending-sitecore-ribbon-with-powershell-scripts/">ribbons and menus</a>, write <a href="http://blog.najmanowicz.com/2012/03/31/2011/11/29/powershell-driven-sitecore-scheduled-tasks/">scripted tasks</a> and <a href="http://blog.najmanowicz.com/2011/12/19/continuous-deployment-in-sitecore-with-powershell/">execute scripts just by launching them from a URL call</a>.</p>
<p>That’s extending Sitecore with PowerShell but what about PowerShell itself?</p>
<p>One of the coolest features introduced in 2.0 is the ability to write your own commandlets. Sure you could always use PowerShell to do it and <a href="http://technet.microsoft.com/en-us/magazine/ff677563.aspx">write commandlets in script</a>. But then the caveat was that you had to attach such commandlets to your own scripts (or put them in the initial script that would have to execute prior to the console). Now I’m talking about writing the real commandlets, just like those that come with the PowerShell console itself. Starting from 2.0 the console does not default to only attach commandlets that come with it, but can also scan other assemblies to attach your commandlets. To add your own all you have to do is well.. write them but then… all you have to do is to use the standard Sitecore include mechanism to enable the console to find them.</p>
<h3>Including my own commandlets into Sitecore PowerShell Console</h3>
<pre class="brush: xml; title: ; notranslate">
&lt;configuration xmlns:patch=&quot;http://www.sitecore.net/xmlconfig/&quot;&gt;
  &lt;sitecore&gt;
    &lt;powershell&gt;
      &lt;commandlets&gt;
	&lt;add type=&quot;*, Cognifide.PowerShell&quot; name=&quot;Cognifide_PowerShell_Commandlets&quot; /&gt;
      &lt;/commandlets&gt;
    &lt;/powershell&gt;
  &lt;/sitecore&gt;
&lt;/configuration&gt;
</pre>
<p>Where the type parameter is just a regular Sitecore type reference with a slight twist – you can use wildcards in it. So with the above example, the console will scan the Cognifide.PowerShell assembly and allow you to use all the commandlet classes that are tagged appropriately.</p>
<h3>How to write a commandlet?</h3>
<p><span id="more-537"></span><br />
Fortunately there is a lot of documentation on that subject from both Microsoft and community a few good starters:</p>
<ul>
<li><a href="http://blogs.msdn.com/b/daiken/archive/2007/02/07/creating-a-windows-powershell-cmdlet-using-the-visual-studio-windows-powershell-templates.aspx">Creating a Windows PowerShell CmdLet using the Visual Studio Windows PowerShell Templates</a></li>
<li><a href="http://msdn.microsoft.com/en-us/magazine/cc163293.aspx">Extend Windows PowerShell With Custom Commands</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.management.automation.cmdlet.aspx">Cmdlet Class</a> – description on MSDN</li>
<li>You might find the <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=2560">PowerShell SDK</a> – helpful in the process</li>
</ul>
<p>But overall all you need to do is to write a class that inherits from the Cmdlet class and implement one or more of the methods:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.management.automation.cmdlet.beginprocessing.aspx">BeginProcessing</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.management.automation.cmdlet.processrecord.aspx">ProcessRecord</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.management.automation.cmdlet.endprocessing.aspx">EndProcessing</a></li>
</ul>
<p>and PowerShell will take care of all of the pipeline processing, parameter handling, binding and so on, you only implement the logic you want your commandlet to perform.</p>
<p>If you want to make your life even easier the Sitecore Console introduces a Cognifide.PowerShell.Shell.Commands.BaseCommand class that does some of the common tasks you might want to perform like getting the <span style="font-family: 'Courier New';">CurrentDrive</span> (Windows Drive or Sitecore Database), learning if your script context is within one of the database (master:\ etc.) IsCurrentDriveSitecore or learning the current full path <span style="font-family: 'Courier New';">CurrentPath</span> or getting a Wildcard to verify if a name matches a user-provided wildcard <span style="font-family: 'Courier New';">GetWildcardPattern</span> allowing you to write into pipeline only if your object matches a wildcard provided by the user <span style="font-family: 'Courier New';">WildcardFilter</span>.</p>
<p>For example a commandlet that retrieves a user from Sitecore and puts it into pipeline looks like following</p>
<pre class="brush: csharp; title: ; notranslate">
using System.Management.Automation;
using System;
using Sitecore.Security.Accounts;

namespace Cognifide.PowerShell.Shell.Commands
{
    [Cmdlet(&quot;Get&quot;, &quot;User&quot;, DefaultParameterSetName = &quot;Name&quot;)]
    public class GetUserCommand : BaseCommand
    {

        [Parameter(ValueFromPipeline = true, Position = 0)]
        public string Name { get; set; }

        [Parameter]
        public SwitchParameter Current { get; set; }

        protected override void ProcessRecord()
        {

            if (Current.IsPresent)
            {
                WriteObject(Sitecore.Context.User, false);
            }

            if (!String.IsNullOrEmpty(Name))
            {
                // from BaseCommand
                WildcardWrite(Name, UserManager.GetUsers(), user =&gt; user.Name);
            }
            else
            {
                WriteObject(UserManager.GetUsers(),true);
            }
        }

    }
}
</pre>
<p>In this case the commandlet can be used in Powershell as a “<span style="font-family: 'Courier New';">Get-User</span>” as defined in the <span style="font-family: 'Courier New';">Cmdlet</span> attribute on the class while <span style="font-family: 'Courier New';">Current</span> and <span style="font-family: 'Courier New';">Name</span> are exposed as its parameters. This is quite cool seeing how you don’t have to do anything about Parsing or binding the arguments – PowerShell does all the plumbing for you. The <span style="font-family: 'Courier New';">Name</span> parameter is bound to the pipeline input which means that you can feed the commandlets with multiple user names (e.g. from a CSV file) and it will turn those into <span style="font-family: 'Courier New';">User</span> objects for its pipeline consumers.</p>
<p>The <span style="font-family: 'Courier New';">Current</span> parameter in turn is interesting for other reasons – shows how to define a switch that can be checked for existense – in this case calling the commandlet like</p>
<pre class="ps1">Get-User -Current</pre>
<p>Will add the currently logged in user ad the output of the commandlet pipeline by its mere inclusion in the command line.</p>
<p>Overall I would strongly encourage you to crack the PowerShell console assembly and see how the existing commandlets work and build your own based on that.</p>
<img src="http://blog.najmanowicz.com/?ak_action=api_record_view&id=537&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://blog.najmanowicz.com/2012/04/03/your-own-powershell-commandlets/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>State of PowerShell for Sitecore for April 2012</title>
		<link>http://blog.najmanowicz.com/2012/03/31/state-of-powershell-for-sitecore-for-april-2012/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=state-of-powershell-for-sitecore-for-april-2012</link>
		<comments>http://blog.najmanowicz.com/2012/03/31/state-of-powershell-for-sitecore-for-april-2012/#comments</comments>
		<pubDate>Sat, 31 Mar 2012 16:08:16 +0000</pubDate>
		<dc:creator>Adam Najmanowicz</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Sitecore]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Solution]]></category>
		<category><![CDATA[Web applications]]></category>

		<guid isPermaLink="false">http://blog.najmanowicz.com/?p=531</guid>
		<description><![CDATA[While I’m updating it on a separate page I thought for the purpose of having a record and further tracking &#8211; it would be interesting to capture the state of the PowerShell knowledge in the Sitecore community here as well. How do I get the PowerShell Console for Sitecore? Download the Console installation package from [...]]]></description>
			<content:encoded><![CDATA[<p>While I’m updating it on a <a href="http://blog.najmanowicz.com/sitecore-powershell-console/">separate page</a> I thought for the purpose of having a record and further tracking &#8211; it would be interesting to capture the state of the PowerShell knowledge in the Sitecore community here as well.</p>
<p align="center"><a href="http://tieulie.com/blog/march-2012-wallpaper-calendar/"><img title="Image Courtesy: Steven Tieulie" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 3px 3px 0px 7px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="Image Courtesy: Steven Tieulie" src="http://blog.najmanowicz.com/wp-content/uploads/2012/03/March-2012-pot_o_gold-calendar-1024x768.png" width="484" height="364" /></a></p>
<h3>How do I get the PowerShell Console for Sitecore?</h3>
<ul>
<li>Download the Console installation package from its <a href="http://trac.sitecore.net/SitecorePowershellConsole">Sitecore Shared Source page</a>. </li>
<li><a href="http://trac.sitecore.net/SitecorePowershellConsole/wiki/Documentation">Introductory documentation to PowerShell console</a> on its Shared Source page. </li>
</ul>
<p><span id="more-531"></span><br />
<h3>Adam&#8217;s (101 level) blogs for PowerShell Console for Sitecore</h3>
<ul>
<li><a href="http://blog.najmanowicz.com/2011/11/17/powershell-console-for-sitecore-what-can-it-do-for-me/">So what PowerShell Console for Sitecore is and what can it do for me?</a> </li>
<li>Sitecore PowerShell Console cheat sheet <a title="Cheat Sheet Part 2" href="http://blog.najmanowicz.com/2012/01/11/sitecore-powershell-console-cheat-sheetpart-1/">Part 1</a> &amp; <a title="Cheat Sheet" href="http://blog.najmanowicz.com/2012/01/23/sitecore-powershell-console-cheat-sheet-part-2/">Part 2</a> </li>
<li><a href="http://blog.najmanowicz.com/2011/11/18/sample-scripts-for-sitecore-powershell-console/">Sample scripts</a> for Sitecore PowerShell Console </li>
</ul>
<h3>How PowerShell console can help you extend Sitecore?</h3>
<ul>
<li><a href="http://blog.najmanowicz.com/2011/12/19/continuous-deployment-in-sitecore-with-powershell/">Continuous deployment in Sitecore with PowerShell</a> </li>
<li><a href="http://blog.najmanowicz.com/2011/11/24/extending-sitecore-ribbon-with-powershell-scripts/">Extending Sitecore ribbon with PowerShell scripts</a> </li>
<li><a title="Permanent Link to PowerShell driven Sitecore scheduled tasks" href="../2011/11/29/powershell-driven-sitecore-scheduled-tasks/" rel="bookmark">PowerShell driven Sitecore scheduled tasks</a> </li>
</ul>
<h3>External Content helpful for Sitecore PowerShell Scripters</h3>
<ul>
<li>Free <a href="http://tumblr.najmanowicz.com/post/5067261138/free-powershell-ebooks">PowerShell EBooks</a> </li>
<li>Sitecore Virtual User Group:&#160; <a href="www.youtube.com/watch?v=GiTiLIOqHYo">An Introduction into PowerShell from a Sitecore .NET Developer</a> </li>
</ul>
<h3>Alternative solutions</h3>
<ul>
<li>PowerShell console in Sitecore Rocks – part of the <a href="http://vsplugins.sitecore.net/default.aspx">Sitecore Rocks extension to Visual Studio</a> </li>
<li>psTerminal – not available yet (currently in development by Andrew Chumachenko of Sitecore UA) – introduced on <a href="http://www.sitecoreug.org/events/Introduction-to-Powershell">Sitecore Virtual User Group Webinar</a>. </li>
</ul>
<h3>The PowerShell co-nerds within Sitecore Community</h3>
<p>Other people that did research in the field, adopted the console early and/or are knowledgeable in the subject:</p>
<ul>
<li><strong>Jakob Christensen</strong> &#8211; Sitecore &#8211; Sitecore Rocks author &#8211; has alternative Sitecore PowerShell console (<a href="https://twitter.com/TheRocksGuy">@TheRocksGuy</a>
<ul><a href="http://vsplugins.sitecore.net/Sitecore-PowerShell.ashx">Sitecore.PowerShell</a> &#8211; Rocks PowerShell commandlets</ul>
</li>
<li><strong>James Gardner</strong> &#8211; PS Console enthusiast &#8211; doing quite advanced stuff with the console (<a href="https://twitter.com/iamdudley">@iamdudley</a>
<ul>
<li><a href="http://sdn.sitecore.net/forum//ShowPost.aspx?PostID=44813">Powershell Console &#8211; editing fields that have never been populated</a> </li>
<li><a href="http://sdn.sitecore.net/forum//ShowPost.aspx?PostID=42978">PowerShell Console script examples for updating built in fields</a> </li>
</ul>
</li>
<li><strong>Nick Wesselman</strong> &#8211; co-author of Sitecore EviBlog (<a href="https://twitter.com/techphoria414">@techphoria414</a> &#8211; PS proponent.
<ul>
<li>Blog &#8211; <a id="phcontent_0_phblogmain_0_ListView1_ctrl1_lnkBlogPostTitle" href="http://www.techphoria414.com/Blog/Change-Item-Templates-With-Sitecore-PowerShell.aspx">Changing Item Templates With Sitecore PowerShell</a> </li>
<li>Forum &#8211; <a href="http://sdn.sitecore.net/forum/ShowPost.aspx?PostID=44494">PowerShell error on Get-Item </a></li>
</ul>
</li>
<li><strong>Alex Shyba</strong> &#8211; Sitecore US &#8211; advanced stuff with PowerShell deployment (<a href="https://twitter.com/alexshyba">@alexshyba</a>
<ul>
<li><a href="http://sitecoreblog.alexshyba.com/2011/12/installing-sitecore-with-powershell.html">Installing Sitecore with PowerShell</a> </li>
</ul>
</li>
<li><strong>Szymon Kuźniak</strong> &#8211; Cognifide &#8211; contributed commandlets to the console (<a href="https://twitter.com/skuzniak">@skuzniak</a>)
<ul>
<li><a href="http://www.cognifide.com/blogs/sitecore/sitecore-profile-cards-the-lazy-way/">Sitecore Profile Cards: The Lazy Way</a> </li>
</ul>
</li>
<li><strong>Marek Musielak</strong> – Cognifide – (<a href="https://twitter.com/MarasM">@MarasM</a>) great thanks to Marek for his help in integrating <a href="http://terminal.jcubic.pl/">JQueryTerminal</a> with the console) </li>
<li>Great thanks to <strong>Lars Nielsen</strong>‏ (<a href="https://twitter.com/ln_sitecore">@ln_sitecore</a>) and <strong>Lars Birkholm Peters</strong> (<a href="https://twitter.com/larsbirkholm">‏@larsbirkholm</a>) for their support and encouragement for the project. </li>
</ul>
<h3>How can I contribute?</h3>
<p>If you have any suggestions please email me: adam [at] najmanowicz.com or post within the <a href="http://sdn.sitecore.net/forum//ShowForum.aspx?ForumID=20">Sitecore Shared Source Forum</a>.</p>
<img src="http://blog.najmanowicz.com/?ak_action=api_record_view&id=531&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://blog.najmanowicz.com/2012/03/31/state-of-powershell-for-sitecore-for-april-2012/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sitecore PowerShell Console cheat sheet &#8211; Part 2</title>
		<link>http://blog.najmanowicz.com/2012/01/23/sitecore-powershell-console-cheat-sheet-part-2/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sitecore-powershell-console-cheat-sheet-part-2</link>
		<comments>http://blog.najmanowicz.com/2012/01/23/sitecore-powershell-console-cheat-sheet-part-2/#comments</comments>
		<pubDate>Mon, 23 Jan 2012 15:04:26 +0000</pubDate>
		<dc:creator>Adam Najmanowicz</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Sitecore]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Solution]]></category>
		<category><![CDATA[Web applications]]></category>

		<guid isPermaLink="false">http://blog.najmanowicz.com/?p=481</guid>
		<description><![CDATA[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: Sitecore PowerShell Console cheat sheet – Part 1. In all cases where it made sense I’ve converted the samples to establish [...]]]></description>
			<content:encoded><![CDATA[<p>Most of this post is also based on the Microsoft’s <a title="Windows PowerShell Quick Reference" href="http://www.microsoft.com/downloads/en/details.aspx?FamilyId=DF8ED469-9007-401C-85E7-46649A32D0E0&amp;displaylang=en" target="_blank">Windows PowerShell Quick Reference</a> however despite the sharing scripting runtimes the nature of the both shells differ considerably as described in the previous post: <a href="http://blog.najmanowicz.com/2012/01/11/sitecore-powershell-console-cheat-sheetpart-1/" target="_blank">Sitecore PowerShell Console cheat sheet – Part 1</a>. In all cases where it made sense I’ve converted the samples to establish them in Sitecore scenarios.</p>
<h2>How to Write Conditional Statements</h2>
<p>To write an If statement use code similar to this:</p>
<pre class="ps1">$page = Get-item .;
$changedBy = $page.&quot;__Updated by&quot;;

if ($changedBy -eq &quot;&quot;)
  { &quot;Unspecified author - a system page?&quot; }
elseif ($changedBy -eq $me)
  { &quot;The page has been last edited by me!&quot; }
else
  { &quot;The page has been last edited by &quot;+ $changedBy }</pre>
<p>Instead of writing a series of If statements you can use a Switch statement, which is equivalent to VBScript’s Select Case statement:</p>
<pre class="ps1">$page = Get-Item .;
switch ($page.Language) {
    &quot;en&quot; {&quot;This version is in English&quot;}
    &quot;pl&quot; {&quot;This version is in Polish&quot;}
    &quot;tlh-KX&quot; {&quot;This version is in Klingon?!&quot;}
    default {&quot;No idea what this language is!&quot;}
  }</pre>
<h2>How to Write For and For Each Loops</h2>
<p><span id="more-481"></span>
<p>To write a For statement use code similar to this:</p>
<pre class="ps1">for ($a = 1; $a -le 10; $a++) {$a}</pre>
<p>By comparison, a For Each statement might look like this:</p>
<pre class="ps1">cd master:\content\home
foreach ($i in Get-ChildItem .)
{ write-host $i.TemplateName }</pre>
<h2>How to Write Do Loops</h2>
<p>To write a Do loop use code like the following, replacing the code between the curly braces with the code to be executed on each iteration of the loop. Oh: and replacing the code inside the parentheses with the loop condition:</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td valign="top" width="47%">
<pre class="ps1">$a = 1
do {$a; $a++}
<b>while</b> ($a -lt 10)</pre>
</td>
<td valign="top" width="6%">&#160;</td>
<td valign="top" width="47%">
<pre class="ps1">$a = 1
do {$a; $a++}
<b>until</b> ($a –gt 10)</pre>
</td>
</tr>
</tbody>
</table>
<h2>How to Use .NET Objects and Classes</h2>
<p>To use a .NET Framework class static method enclose the class name in square brackets, then separate the class name and the method using a pair of colons:</p>
<pre class="ps1">$master = <b>[Sitecore.Configuration.Factory]</b>::GetDatabase(&quot;master&quot;);
$homeItem = $master.GetItem(&quot;/sitecore/content/home&quot;);
$sample = $master.Templates[&quot;sample/sample item&quot;];
$myItem = $homeItem.Add(&quot;MyItem&quot;, $sample);</pre>
<p>To create an object reference to a .NET Framework object use the New-Object cmdlet:</p>
<pre class="ps1">$item = Get-Item &quot;master:\media library\Files\Sample&quot;;
<b>$mediaItem = New-Object `
                   -type Sitecore.Data.Items.MediaItem
                   -argumentlist $item</b></pre>
<p><b>Note</b>. This is a cursory overview of working with .NET. The two techniques shown here will not necessarily work with all .NET classes.</p>
<h2>How to Select Properties</h2>
<p>To work with or display specified properties of a collection, pipe the returned results to the Select-Object cmdlet:</p>
<pre class="ps1">Get-Item master:\content\Home | `
  Select-Object DisplayName, TemplateName</pre>
<h2>How to Sort Data</h2>
<p>To sort data returned by Windows PowerShell simply pipe that data to the Sort-Object cmdlet, specifying the property you want to sort by:</p>
<pre class="ps1">Get-ChildItem -recurse |
    <b>Sort-Object DisplayName</b> |
    Select-Object DisplayName, TemplateName</pre>
<p>You can also add the –descending or -ascending parameters to specify a sort order:</p>
<pre class="ps1">Get-ChildItem -recurse |
    <b>Sort-Object PageSaved -descending</b> |
    Select-Object DisplayName, __Updated, &quot;__Updated By&quot;</pre>
<p>You can even sort by multiple properties:</p>
<pre class="ps1">Get-ChildItem -recurse |
    <b>Sort-Object TemplateName, &quot;__Updated By&quot;</b> |
    Select-Object TemplateName, &quot;__Updated By&quot;, DisplayName</pre>
<h2>How to Work with WMI</h2>
<p>To get computer information using WMI call the Get-WMIObject cmdlet followed by the class name:</p>
<pre class="ps1">Get-WMIObject Win32_BIOS</pre>
<p>If the class you are interested in does not reside in the cimv2 namespace simply include the <b>–namespace</b> parameter:</p>
<pre class="ps1">Get-WMIObject SystemRestore `
    -namespace root\default</pre>
<p>To access data on another computer use the <b>–computername</b> parameter:</p>
<pre class="ps1">Get-WMIObject Win32_BIOS `
    –computername atl-ws-01</pre>
<p>To limit returned data, use a WQL query and the <b>–query</b> parameter:</p>
<pre class="ps1">Get-WMIObject -query `
    &quot;Select * From Win32_Service `
        Where State = 'Stopped'&quot;</pre>
<h2>How to “Interrogate” an Object</h2>
<p>To get information about the properties and methods of an object retrieve an instance of that object and then “pipe” the object to the <b>Get-Member</b> cmdlet. For example, this command returns the properties and methods available when working with processes:</p>
<pre class="ps1">Get-Item . | Get-Member</pre>
<p><strong>More tips coming soon… </strong>In the mean time please download the fresh version of the plugin with the latest improvements:</p>
<h2 align="center"><a title="Sitecore Powershell console on Shared Source" href="http://trac.sitecore.net/SitecorePowershellConsole" target="_blank">[Download &amp; Enjoy]</a></h2>
<p>All feedback appreciated!</p>
<blockquote style="padding-right: 16px !important">
<p><font color="#ff0000"><em><img style="background-image: none; border-right-width: 0px; margin: 3px 20px 0px 7px; padding-left: 0px; padding-right: 0px; display: inline; float: left; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Aperture_Science" border="0" alt="Aperture_Science" align="left" src="http://blog.najmanowicz.com/wp-content/uploads/2011/05/Aperture_Science_thumb.png" width="150" height="150" />Science isn&#8217;t about why, it&#8217;s about why not!?</em> </font><font color="#ff0000"><em>You ask: why is so much of our science dangerous? </p>
<p>I say: why not marry safe science if you love it so much. In fact, why not invent a special safety door that won&#8217;t hit you in the butt on the way out, because YOU ARE FIRED!</em></font></p>
<p><font color="#ff0000"><em>Yes you, box your stuff, out the front door, parking lot, car, goodbye. </p>
<p></em></font></p>
<p align="right"><font color="#ff0000">&#8211; <strong><a href="http://apscience.wikia.com/wiki/Cave_Johnson" target="_blank">Cave Johnson</a></strong> </font></p>
</blockquote>
<img src="http://blog.najmanowicz.com/?ak_action=api_record_view&id=481&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://blog.najmanowicz.com/2012/01/23/sitecore-powershell-console-cheat-sheet-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Sitecore PowerShell Console cheat sheet &#8211; Part 1</title>
		<link>http://blog.najmanowicz.com/2012/01/11/sitecore-powershell-console-cheat-sheetpart-1/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sitecore-powershell-console-cheat-sheetpart-1</link>
		<comments>http://blog.najmanowicz.com/2012/01/11/sitecore-powershell-console-cheat-sheetpart-1/#comments</comments>
		<pubDate>Wed, 11 Jan 2012 20:36:11 +0000</pubDate>
		<dc:creator>Adam Najmanowicz</dc:creator>
				<category><![CDATA[Code Samples]]></category>
		<category><![CDATA[Downloadable]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Sitecore]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Solution]]></category>
		<category><![CDATA[Web applications]]></category>

		<guid isPermaLink="false">http://blog.najmanowicz.com/?p=473</guid>
		<description><![CDATA[I’m realizing time and time again that the learning curve for PowerShell can be steep without a proper guidance. While most people I talk to are very excited about the concept they become discouraged after a having some tries and not realizing its full potential. Therefore I decided it’s worth spending some time introducing some [...]]]></description>
			<content:encoded><![CDATA[<p>I’m realizing time and time again that the learning curve for PowerShell can be steep without a proper guidance. While most people I talk to are very excited about the concept they become discouraged after a having some tries and not realizing its full potential. Therefore I decided it’s worth spending some time introducing some basic principles to help scripting alleviate some of the initial pains.    </p>
<p>I have <a href="http://tumblr.najmanowicz.com/post/5067261138/free-powershell-ebooks" target="_blank">gathered some literature available for free about the topic of PowerShell in general you might want to read</a>, but I also think that a distillation of the basic concepts is really important so you can have some quick wins while you begin your PowerShell journey.</p>
<p>A great deal of this post is a <a href="http://blog.najmanowicz.com/2011/05/09/powershell-for-episerver-cheat-sheet-part-1/" target="_blank">port of my older post</a> for similar console for EPiServer, but since the differences are significant enough to confuse Sitecore developers if I sent them to the original version, I’ve decided to create a proper Sitecore cheat sheet.&#160;&#160; Most of this is based on the Microsoft’s <a title="Windows PowerShell Quick Reference" href="http://www.microsoft.com/downloads/en/details.aspx?FamilyId=DF8ED469-9007-401C-85E7-46649A32D0E0&amp;displaylang=en" target="_blank">Windows PowerShell Quick Reference</a> 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).</p>
<table border="1" cellspacing="2" cellpadding="12">
<tbody>
<tr>
<th valign="top" width="50%">Windows PowerShell</th>
<th valign="top" width="50%">PowerShell Console for Sitecore</th>
</tr>
<tr>
<td valign="top"><strong>Interactive</strong> – command can ask for confirmations and can be aborted. User can be solicited to provide input.</td>
<td valign="top"><strong>Batch</strong> – 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.</td>
</tr>
<tr>
<td valign="top">Supports command line arguments for running scripts.</td>
<td valign="top">All arguments are defined directly within the script or derived from context automatically.</td>
</tr>
<tr>
<td valign="top">Can access any file depending on the rights of the user.</td>
<td valign="top">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.</td>
</tr>
</tbody>
</table>
<p>That said, I considered that enough of the Reference document is irrelevant in the Sitecore 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.</p>
<p>The content &amp; samples of the original cheat sheet has been adjusted to more closely reflect scenarios usable for an Sitecore admin or developer.</p>
<h2>How to get help</h2>
<blockquote><p align="center"><em>Give a man a fish and you feed him for a day. Teach a man to fish and you feed him for a lifetime.</em></p>
</blockquote>
<p><span id="more-473"></span>
<p>By this principle – PowerShell by itself comes with an extensive help system. And the Sitecore implementation takes nothing away from it. Should you find yourself wondering the following is your friend.</p>
<p>To discover commandlet’s syntax you can use something like:</p>
<table border="0" cellspacing="0" cellpadding="0" width="97%">
<tbody>
<tr>
<td valign="top" width="47%">
<pre class="ps1">Get-Help Get-Item –Full</pre>
</td>
<td valign="top" width="6%">&#160;</td>
<td valign="top" width="47%">
<pre class="ps1">Get-Help ForEach-Object –Verbose</pre>
</td>
</tr>
</tbody>
</table>
<p>You can learn more about the help system by being slightly recursive <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blog.najmanowicz.com/wp-content/uploads/2012/01/wlEmoticon-smile.png" /></p>
<pre class="ps1">Get-Help Get-Help –Full</pre>
<p>There is a lot of discoverability within the environment. For example to learn about commandlets available to you you can try experimenting with these:</p>
<table border="0" cellspacing="0" cellpadding="0" width="97%">
<tbody>
<tr>
<td valign="top" width="47%">
<pre class="ps1">Get-Command -CommandType Cmdlet</pre>
</td>
<td valign="top" width="6%">&#160;</td>
<td valign="top" width="47%">
<pre class="ps1">Get-Command Get-*</pre>
</td>
</tr>
</tbody>
</table>
<p>You can discover what capabilities an object you got in pipeline possesses by using Get-Member e.g.:</p>
<pre class="ps1">Get-Item master:\ | Get-Member</pre>
<h1>And here go the Sitecore specific tips</h1>
<h2>How to work with items</h2>
<p>To switch to the desired database item you would use the following:</p>
<table border="0" cellspacing="0" cellpadding="0" width="97%">
<tbody>
<tr>
<td valign="top" width="47%">
<pre class="ps1">cd master:\</pre>
</td>
<td valign="top" width="6%">&#160;</td>
<td valign="top" width="47%">
<pre class="ps1">cd core:\content\Applications</pre>
</td>
</tr>
</tbody>
</table>
<p>The environment deliberately skips the “Sitecore” root in the tree as it provides no value to give the script access to the item and in fact unnecessarily lengthens each path so the “Sitecore” root is treated as the drive root. You can still access it as follows:</p>
<pre class="ps1">cd master:\
Get-Item .</pre>
<h2>How to get Current Item</h2>
<p>To get the page for the location you’re in you can use:</p>
<pre class="ps1">Get-Item .</pre>
<h2>How to get Current Page’s children</h2>
<p>To get the children of the page you’re currently in:</p>
<pre class="ps1">Get-ChildItem</pre>
<p>To get the children of the page you’re currently in and all of its children children (whole branch):</p>
<pre class="ps1">Get-ChildItem –recurse</pre>
<h2>How to Modify an item</h2>
<pre class="ps1">Get-Item . | ForEach-Object { $_.Text = “&lt;p&gt;Hello World&lt;/p&gt;” }</pre>
<p>or in short:</p>
<pre class="ps1">Get-Item . |% { $_.Text = “&lt;p&gt;Hello World&lt;/p&gt;” }</pre>
<h2>How to restart the application</h2>
<p>To restart the application use the following command:</p>
<pre class="ps1">Restart-Application</pre>
<h2>How to get system properties and environment variables</h2>
<p>Some more important variables are mapped onto the PowerShell variables by the plugin. Notable variables (value depending on your server configuration):</p>
<table border="1" cellspacing="1" cellpadding="5">
<tbody>
<tr>
<td valign="top" width="34%"><strong>Name</strong></td>
<td valign="top" width="65%">Sample value</td>
</tr>
<tr>
<td valign="top" width="34%">$AppPath</td>
<td valign="top" width="65%">C:\inetpub\wwwroot\CognifideShowcase\</td>
</tr>
<tr>
<td valign="top" width="34%">$AppVPath</td>
<td valign="top" width="65%">/ (app virtual folder)</td>
</tr>
<tr>
<td valign="top" width="34%">$tempPath</td>
<td valign="top" width="65%">C:\Windows\TEMP</td>
</tr>
<tr>
<td valign="top" width="34%">$tmpPath</td>
<td valign="top" width="65%">C:\Windows\TEMP</td>
</tr>
<tr>
<td valign="top" width="34%">$me</td>
<td valign="top" width="65%">sitecore\admin</td>
</tr>
</tbody>
</table>
<p><strong></strong></p>
<p>You can list all PowerShell variables by using:</p>
<pre class="ps1">Get-Variable *</pre>
<p>Additionally you can list all environment variables by using:</p>
<pre class="ps1">[System.Environment]::GetEnvironmentVariables()</pre>
<p>and get the value of a specific variable with e.g.:</p>
<pre class="ps1">[System.Environment]::GetEnvironmentVariable(&quot;ComputerName&quot;)</pre>
<h1>PowerShell Language and environment specific tips</h1>
<h2>How to Insert Comments</h2>
<p>To insert a comment, use the pound sign (#):</p>
<pre class="ps1"># This is a comment, not a line to be run.</pre>
<h2>How to Insert Line Breaks</h2>
<p>To insert a line break into a Windows PowerShell script use the backtick (`) :</p>
<pre class="ps1">$b = `
&quot;This is a continuation of the line.&quot;</pre>
<p>You can also break a line at the pipe separator (|) character (assuming your line uses the pipeline):</p>
<pre class="ps1">Get-ChildItem C:\Scripts |
Sort-Object Length –Descending</pre>
<h2>How to Create Multi-Command Lines</h2>
<p>To put multiple commands on a single line, separate those commands using a semicolon:</p>
<pre class="ps1">$a = 1,2,3,4,5; $b = $a[2]; $b</pre>
<p><strong>Hint.</strong> This script writes-out the value of <strong>$b</strong> which is <strong>3</strong></p>
<h2>How to Make Comparisons</h2>
<p>Windows PowerShell cmdlets (like <strong>Where-Object</strong>) use a special set of comparison operators, including those shown in the following table.</p>
<p>Each of these operators can be made case sensitive by adding a <strong>c</strong> immediately after the hyphen. For example, <strong>-ceq </strong>represents the case-sensitive equals operator; <strong>-clt</strong> is the case-sensitive less than operator.</p>
<table border="1" cellspacing="1" cellpadding="5">
<tbody>
<tr>
<td valign="top" width="34%"><strong>-lt</strong></td>
<td valign="top" width="65%">Less than</td>
</tr>
<tr>
<td valign="top" width="34%"><strong>-le</strong></td>
<td valign="top" width="65%">Less than or equal to</td>
</tr>
<tr>
<td valign="top" width="34%"><strong>-gt</strong></td>
<td valign="top" width="65%">Greater than</td>
</tr>
<tr>
<td valign="top" width="34%"><strong>-ge</strong></td>
<td valign="top" width="65%">Greater than or equal to</td>
</tr>
<tr>
<td valign="top" width="34%"><strong>-eq</strong></td>
<td valign="top" width="65%">Equal to</td>
</tr>
<tr>
<td valign="top" width="34%"><strong>-ne</strong></td>
<td valign="top" width="65%">Not equal to</td>
</tr>
<tr>
<td valign="top" width="34%"><strong>-like</strong></td>
<td valign="top" width="65%">Like (uses wildcards for matching)</td>
</tr>
<tr>
<td valign="top" width="34%"><strong>-notlike</strong></td>
<td valign="top" width="65%">Not like (uses wildcards for matching)</td>
</tr>
</tbody>
</table>
<p><strong></strong></p>
<p><strong></strong></p>
<h2>How to Read a Text File</h2>
<p>To read the contents of a text file into a variable, call the <strong>Get-Content</strong> cmdlet followed by the path to the text file:</p>
<pre class="ps1">$a = Get-Content C:\Scripts\Test.txt</pre>
<p>Each line in the file ends up as an item in the array $a. If you want to access a single line in the file you can simply specify the index number corresponding to that line:</p>
<pre class="ps1">$a[0]</pre>
<p>This command echoes back the <em>last </em>line in $a:</p>
<pre class="ps1">$a[-1]</pre>
<p><strong>Bonus</strong>. To determine the number of lines, words, and characters in a text file use this command:</p>
<pre class="ps1">Get-Content c:\scripts\test.txt |
measure-object -line -word -character</pre>
<h2>How to Write to a Text File</h2>
<p>To save data to a text file use the <strong>Out-File</strong> cmdlet:</p>
<pre class="ps1">Get-Item . | Out-File C:\Scripts\Test.txt</pre>
<p>To append data to an existing file, add the –<strong>append</strong> parameter:</p>
<pre class="ps1">Get-Item . | Out-File C:\Scripts\Test.txt –append</pre>
<p><strong>Attention. </strong>Unlike in the regular Windows PowerShell console you cannot use the MS-DOS redirection characters (&gt; for write, &gt;&gt; for append) when using Sitecore hosted PowerShell.</p>
<p>Another option is to use the <strong>Export-CSV</strong> cmdlet to save data as a comma-separated-values file:</p>
<pre class="ps1">Get-Item . | Export-CSV C:\Scripts\Test.txt</pre>
<p><strong>More tips coming soon… </strong>In the mean time please download the fresh version of the plugin with the latest improvements:</p>
<h2 align="center"><a title="Download Powershell console" href="http://trac.sitecore.net/SitecorePowershellConsole" target="_blank">[Download &amp; Enjoy]</a> </h2>
<p>All feedback appreciated!</p>
<img src="http://blog.najmanowicz.com/?ak_action=api_record_view&id=473&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://blog.najmanowicz.com/2012/01/11/sitecore-powershell-console-cheat-sheetpart-1/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Continuous deployment in Sitecore with PowerShell</title>
		<link>http://blog.najmanowicz.com/2011/12/19/continuous-deployment-in-sitecore-with-powershell/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=continuous-deployment-in-sitecore-with-powershell</link>
		<comments>http://blog.najmanowicz.com/2011/12/19/continuous-deployment-in-sitecore-with-powershell/#comments</comments>
		<pubDate>Mon, 19 Dec 2011 11:28:03 +0000</pubDate>
		<dc:creator>Adam Najmanowicz</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CMS UX]]></category>
		<category><![CDATA[Code Samples]]></category>
		<category><![CDATA[Continuous Deployment]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Sitecore]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Web applications]]></category>

		<guid isPermaLink="false">http://blog.najmanowicz.com/?p=464</guid>
		<description><![CDATA[A few days back a budy from our Sitecore team has alerted me to this interesting question on StackOverflow which asks for automation of content promotion from one Sitecore instance to another. He suggested &#8211; and rightly so – that the PowerShell Console could be used in that scenario. While this was always possible by [...]]]></description>
			<content:encoded><![CDATA[<p>A few days back a <a href="http://stackoverflow.com/users/3205/skolima" target="_blank">budy</a> from our Sitecore team has alerted me to this interesting question on <a href="http://stackoverflow.com/questions/8414482/is-it-possible-to-build-a-sitecore-data-package-from-command-line-or-outside-of" target="_blank">StackOverflow</a> which asks for automation of content promotion from one Sitecore instance to another. He suggested &#8211; and rightly so – that the <a href="http://trac.sitecore.net/SitecorePowershellConsole" target="_blank">PowerShell Console</a> could be used in that scenario. While this was always possible by simply writing it as a PowerShell code the latest version of the console added a few commandlets making building packages much easier.</p>
<p>The easiest approach is to build the package visually in the package designer, save it and then simply use the console to read it and generate the installation zip like:</p>
<pre class="ps1">get-package &quot;powershell console.xml&quot; `
  | Export-Package -FileName &quot;PowerShell Console.zip&quot; <b>-Zip</b></pre>
<p>That’s fine in most cases but if you have some more complex scenarios or want to generate some custom packages – you might want to generate packages directly in PowerShell. </p>
<p>To Create a Package you simply use:</p>
<pre class="ps1">$package = new-package &quot;Test Package&quot;;</pre>
<p>Now that you have that package you might want to add some files and items to it.</p>
<p>Let&#8217;s add for example our item templates by querying the master database and creating a dynamic item source: </p>
<pre class="ps1">$TemplatesSource = get-childitem &quot;master:/templates/Cognifide&quot; `
  | New-ItemSource &quot;Cognifide Templates&quot;;</pre>
<p>And subsequently add it to our new package: </p>
<pre class="ps1">$package.Sources.Add($TemplatesSource);</pre>
<p>While that by itself is fairly useful, the really cool part is that you have a full flexibility of PowerShell at your disposal when you create a source with static items. Let’s say you want to add all items of template “Article Template” that reside anywhere under your “home” node … now that would require quite a bit of clicking in the Package Designer, but is trivial with the PowerShell Console:</p>
<pre class="ps1">$ArticlesSource = get-childitem master:/content/home/about-us/* -recurse `
  | where-object { $_.TemplateName -match &quot;ArticleTemplate&quot; } `
  | New-ExplicitItemSource &quot;Cognifide Articles&quot;;

$package.Sources.Add($ArticlesSource);</pre>
<p>You can specify any automation or filter you can think of to your <strong>Get-ChildItem</strong>, and you really don’t have to skimp on the number of data sources – after all you can re-generate your package at any time!</p>
<p>Similarly you can do this to the files on disk. Let’s say – you want to add all .aspx, .ascx and .ashx files, just to make sure your deployment features all the latest code and for the sake of this example let’s assume your UI elements are located in the <em>Layouts</em> folder under your web application:</p>
<pre class="ps1">$LayoutsPath = $AppPath+&quot;layouts\*&quot;
$Layouts = get-childitem $LayoutsPath -include &quot;*.as?x&quot; -recurse -force `
  | New-ExplicitFileSource &quot;My Layouts&quot;;
$package.Sources.Add($Layouts);</pre>
<p>Easy enough… now let’s add everything that is within the bin folder as a dynamic file source:</p>
<pre class="ps1">$BinFolder = New-FileSource &quot;Bin Folder&quot; -Root &quot;/bin&quot;
$package.Sources.Add($BinFolder);</pre>
<p>That is it really… you may want to specify your package metadata which you would do like:</p>
<pre class="ps1">$package.Metadata.Author = &quot;Auto generated &quot; + `
  [DateTime]::Now.ToShortDateString();
$package.Metadata.Comment = &quot;Isn't it cool?!&quot;;
$package.Metadata.Publisher = &quot;Cognifide&quot;;</pre>
<p>and then save it for later opening in package designer:</p>
<pre class="ps1">$package | Export-Package -FileName &quot;test package.xml&quot;</pre>
<p>alternatively you can open such package as specified earlier</p>
<pre class="ps1">get-package &quot;test package.xml&quot;</pre>
<p>if you ever wanted to add more sources to it or export as a zip file to be imported with the assets in your target environment:</p>
<pre class="ps1">$package | Export-Package -FileName &quot;test package.zip&quot; -Zip</pre>
<p>… now on your target machine you need to upload your package to the Data\Packages folder. But then to install it all it takes is:</p>
<pre class="ps1">Import-Package &quot;test package.zip&quot;</pre>
<p>Obviously all of it can be hooked to ribbon, context items, or be scheduled… but I get ahead of myself&#8230;</p>
<h2>So how does it all relate to continuous deployment?</h2>
<p>All of this can be completely automated, all you need to do is create a Script item as described in <a href="http://blog.najmanowicz.com/2011/11/24/extending-sitecore-ribbon-with-powershell-scripts/" target="_blank">one of my previous posts</a> and call the PowerShell execution URL referencing your script from your CruiseControl server or whichever continuous integration product you use in a fashion similar to:</p>
<pre>http://myhost/Console/Layouts/PowerShellResults.aspx?scriptId={1680E211-BD28-49BE-82FB-DA7232814C62}&amp;scriptDb=web</pre>
<p>You need to deal with the fact that you are most probably not logged in with your continuous delivery environment – in this case probably best approach is to use the web database or the script item my turn out to be unavailable to you and the script will not execute.</p>
<p>Now in your source environment your script will create the package and upload it to an FTP server (there is plenty of ways to do this from PowerShell… you can find a <a href="http://stackoverflow.com/questions/1867385/upload-files-with-ftp-using-powershell" target="_blank">couple of samples on Stack Overflow</a>) and subsequently <a href="http://stackoverflow.com/questions/508565/how-to-make-an-authenticated-web-request-in-powershell" target="_blank">call a second part of the script on the target server</a>.</p>
<p>On the Target server – a complementary script will be executed in the similar fashion – by the originating server and if you don’t have direct access to the file on the FTP server you’ve just uploaded – you can download it and import the package.</p>
<p>Now if you integrate the script with a ribbon in Content Editor on the source server (<a href="http://blog.najmanowicz.com/2011/11/24/extending-sitecore-ribbon-with-powershell-scripts/" target="_blank">like described in the previous post</a>) you can have a one-click-deployment solution on your dev machine, but then the REALLY cool part would be to integrate it with the context menu (<a href="http://blog.najmanowicz.com/2011/11/22/context-powershell-scripts-for-sitecore/" target="_blank">as described in this post</a>) and be able to push parts of the site to production with a single click! Not to mention your nightlies can really be nightlies if you do it using the <a href="http://blog.najmanowicz.com/2011/11/29/powershell-driven-sitecore-scheduled-tasks/" target="_blank">scheduled tasks integration</a>.</p>
<img src="http://blog.najmanowicz.com/?ak_action=api_record_view&id=464&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://blog.najmanowicz.com/2011/12/19/continuous-deployment-in-sitecore-with-powershell/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PowerShell driven Sitecore scheduled tasks</title>
		<link>http://blog.najmanowicz.com/2011/11/29/powershell-driven-sitecore-scheduled-tasks/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-driven-sitecore-scheduled-tasks</link>
		<comments>http://blog.najmanowicz.com/2011/11/29/powershell-driven-sitecore-scheduled-tasks/#comments</comments>
		<pubDate>Tue, 29 Nov 2011 16:21:58 +0000</pubDate>
		<dc:creator>Adam Najmanowicz</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.najmanowicz.com/2011/11/29/powershell-driven-sitecore-scheduled-tasks/</guid>
		<description><![CDATA[So now that you can easily create the menus and ribbons executing PowerShell scripts, it might be a good time to do some more administrative tasks… let’s start with scheduled tasks. I’m not going to go deep into the task scheduling, you can find an excellent post by John West on his blog regarding task [...]]]></description>
			<content:encoded><![CDATA[<p>So now that you can easily create the <a href="http://blog.najmanowicz.com/2011/11/22/context-powershell-scripts-for-sitecore/" target="_blank">menus</a> and <a href="http://blog.najmanowicz.com/2011/11/24/extending-sitecore-ribbon-with-powershell-scripts/" target="_blank">ribbons</a> executing PowerShell scripts, it might be a good time to do some more administrative tasks… let’s start with scheduled tasks. I’m not going to go deep into the task scheduling, you can find an <a href="http://www.sitecore.net/deutsch/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/11/All-About-Sitecore-Scheduling-Agents-and-Tasks.aspx" target="_blank">excellent post by John West on his blog regarding task scheduling</a>. Currently the PowerShell module supports one of the ways described in the post – the section describing how to configure them is called “Scheduled Tasks” in the blog.</p>
<p>The module comes with an out-of-the-box PowerShell script command as you can see</p>
<p align="center"><a href="http://blog.najmanowicz.com/wp-content/uploads/2011/11/PowerShellScheduledTaskCommand.png" rel="lightbox[463]" title="PowerShellScheduledTaskCommand"><img style="margin: 3px 3px 0px 7px; display: inline" title="PowerShellScheduledTaskCommand" alt="PowerShellScheduledTaskCommand" src="http://blog.najmanowicz.com/wp-content/uploads/2011/11/PowerShellScheduledTaskCommand_thumb.png" width="252" height="459" /></a></p>
<p>You don’t need to create any additional commands, instead you only need to create a script and a schedule for it and the existing command will handle all of them. In my example I wanted to trim all recycle bin items every night.</p>
<p>Let’s get cracking…</p>
<p><span id="more-463"></span>
<p>First you need a script that will accomplish the task. The module automatically creates a Scripts folder in the following location: <strong>/sitecore/system/Modules/Scripts/</strong>. It probably is best if you stick to putting your scripts there. The Insert options for it are limited to scripts and folders so you can organize your scripts into subfolders if the number will grow significantly.</p>
<p>In my case the script part will be fairly simple:</p>
<p align="center"><a href="http://blog.najmanowicz.com/wp-content/uploads/2011/11/EmptyRecycleBinScript.png" rel="lightbox[463]" title="EmptyRecycleBinScript"><img style="background-image: none; border-right-width: 0px; margin: 3px 3px 0px 7px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="EmptyRecycleBinScript" border="0" alt="EmptyRecycleBinScript" src="http://blog.najmanowicz.com/wp-content/uploads/2011/11/EmptyRecycleBinScript_thumb.png" width="400" height="250" /></a></p>
<p>The <strong>Popup window</strong> and <strong>Pre-execution warning</strong> settings in this case have no meaning as the script has no means of providing this kind of feedback as it’s executed in a background thread.</p>
<p>Now create a schedule for your script in <strong>/sitecore/system/Tasks/Schedules/</strong>:</p>
<p align="center"><a href="http://blog.najmanowicz.com/wp-content/uploads/2011/11/EmptyRecycleBinSchedule.png" rel="lightbox[463]" title="EmptyRecycleBinSchedule"><img style="background-image: none; border-right-width: 0px; margin: 3px 3px 0px 7px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="EmptyRecycleBinSchedule" border="0" alt="EmptyRecycleBinSchedule" src="http://blog.najmanowicz.com/wp-content/uploads/2011/11/EmptyRecycleBinSchedule_thumb.png" width="400" height="303" /></a></p>
<p>I strongly encourage that you read more about how task scheduling works in <a href="http://www.sitecore.net/deutsch/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/11/All-About-Sitecore-Scheduling-Agents-and-Tasks.aspx" target="_blank">Johns blog</a>. An additional feature you might find useful since there is no UI component to running scheduled tasks is the new <strong>Write-Log</strong> commandlet, which wors similarly to <strong>Write-Host</strong> but instead writes to Sitecore diagnostic logs. The syntax is as follows</p>
<pre class="ps1">Write-Log [[-Object] &lt;Object&gt;] [-Separator &lt;Object&gt;]
  [-Log &lt;LogNotificationLevel&gt;]</pre>
<p>So for example to write an info message you can use:</p>
<pre class="ps1">Write-Log “Recycle bin clear scheduled task started”</pre>
<p>Similarly you can write a Debug message like:</p>
<pre class="ps1">Write-Log –Log Debug “This is a debug message”</pre>
<p>This supports all of the common log types like: Debug, Error, Fatal, Warning &amp; Info – if no log type specified – Info will be used.</p>
<p>The solution requires the latest <a href="http://trac.sitecore.net/SitecorePowershellConsole">Sitecore PowerShell Console</a> (1.2.0) from <a href="http://www.cognifide.com/">Cognifide</a>, available for free from <a href="http://trac.sitecore.net/SitecorePowershellConsole">Sitecore Shared Source</a> site.</p>
<p>All feedback appreciated!</p>
<img src="http://blog.najmanowicz.com/?ak_action=api_record_view&id=463&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://blog.najmanowicz.com/2011/11/29/powershell-driven-sitecore-scheduled-tasks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extending Sitecore ribbon with PowerShell scripts</title>
		<link>http://blog.najmanowicz.com/2011/11/24/extending-sitecore-ribbon-with-powershell-scripts/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=extending-sitecore-ribbon-with-powershell-scripts</link>
		<comments>http://blog.najmanowicz.com/2011/11/24/extending-sitecore-ribbon-with-powershell-scripts/#comments</comments>
		<pubDate>Thu, 24 Nov 2011 10:08:40 +0000</pubDate>
		<dc:creator>Adam Najmanowicz</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Samples]]></category>
		<category><![CDATA[Downloadable]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Sitecore]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Solution]]></category>
		<category><![CDATA[Web applications]]></category>

		<guid isPermaLink="false">http://blog.najmanowicz.com/?p=454</guid>
		<description><![CDATA[Sitecore is built from the grounds up with extendibility in mind. Be that plugging into any place in its internal pipelines or any aspect of its User eXperience, therefore when I’ve managed to extend it’s context menu, I expected to have no problems whatsoever doing the same to its ribbon. Mind you I was right… [...]]]></description>
			<content:encoded><![CDATA[<p>Sitecore is built from the grounds up with extendibility in mind. Be that plugging into any place in its internal pipelines or any aspect of its User eXperience, therefore when I’ve managed to <a title="Context PowerShell scripts for Sitecore" href="http://blog.najmanowicz.com/2011/11/22/context-powershell-scripts-for-sitecore/" target="_blank">extend it’s context menu</a>, I expected to have no problems whatsoever doing the same to its ribbon. Mind you I was right…</p>
<p>Using the <a title="Sitecore PowerShell Console" href="http://trac.sitecore.net/SitecorePowershellConsole" target="_blank">PowerShell Console Module</a> it took me less than 10 minutes total to add a nice piece of functionality that I thought was missing – Publish items I have modified.</p>
<p align="center"><a href="http://blog.najmanowicz.com/wp-content/uploads/2011/11/ContextScriptsRibbon.png" rel="lightbox[454]" title="ContextScriptsRibbon"><img style="background-image: none; border-right-width: 0px; margin: 3px 3px 0px 7px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="ContextScriptsRibbon" border="0" alt="ContextScriptsRibbon" src="http://blog.najmanowicz.com/wp-content/uploads/2011/11/ContextScriptsRibbon_thumb.png" width="327" height="275" /></a></p>
<p>Similarly to <a title="Context PowerShell Scripts" href="http://blog.najmanowicz.com/2011/11/22/context-powershell-scripts-for-sitecore/" target="_blank">extending context menu</a> – first I’ve created the script I wanted to execute that will take the current item and it’s sub-items and publish them by adding a new script item using the <strong><em>/sitecore/templates/Cognifide/PowerShell Script</em></strong> template in the core database. I’ve put it in the same place I store all my my scripts &#8211; in the <strong><em>/sitecore/content/Applications/PowerShell Console/Scripts</em></strong> branch but feel free to store them anywhere in the tree.</p>
<ul>
<li>Filled in the Script body part with my script. </li>
<li>I decided I want to see the publishing results as I want to verify if the items I expected got published. </li>
</ul>
<p><a href="http://blog.najmanowicz.com/wp-content/uploads/2011/11/ContextScriptRibbonBody.png" rel="lightbox[454]" title="ContextScriptRibbonBody"><img style="background-image: none; border-right-width: 0px; margin: 3px auto 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="ContextScriptRibbonBody" border="0" alt="ContextScriptRibbonBody" src="http://blog.najmanowicz.com/wp-content/uploads/2011/11/ContextScriptRibbonBody_thumb.png" width="350" height="191" /></a></p>
<p>Now the UI integration bits…</p>
<p>Since I wanted it nicely integrated with the publish button &#8211; I’ve created a <strong><em>Publish My Items</em></strong> item of template <strong><em>/sitecore/templates/System/Menus/Menu item</em></strong> within the <strong><em>/sitecore/content/Applications/Content Editor/Menues/Publish/</em></strong> branch in the core database, set it’s icon and reference the script item in the <strong><em>Message</em></strong> field using the following pattern:</p>
<pre>item:executescript(id=$Target,script={0937769B-998D-4580-B9FE-730C4CDABECD},scriptDb=core)</pre>
<p>where the <strong><em>script</em></strong> guid is the ID of your script and the <strong><em>scriptDb</em></strong> is the database the script is located in.</p>
<p><a href="http://blog.najmanowicz.com/wp-content/uploads/2011/11/ContextScriptsRibbonBinding.png" rel="lightbox[454]" title="ContextScriptsRibbonBinding"><img style="background-image: none; border-right-width: 0px; margin: 3px auto 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="ContextScriptsRibbonBinding" border="0" alt="ContextScriptsRibbonBinding" src="http://blog.najmanowicz.com/wp-content/uploads/2011/11/ContextScriptsRibbonBinding_thumb.png" width="350" height="232" /></a></p>
<p>That’s it really. You can <a href="http://www.najmanowicz.com/blog_bin/PublishMyItems.zip" target="_blank">download the solution</a> but I would strongly recommend you try the manual approach – it’s really exciting to see the puzzles click in.</p>
<p>The solution requires the <a href="http://trac.sitecore.net/SitecorePowershellConsole" target="_blank">Sitecore PowerShell Console</a> from <a href="http://www.cognifide.com/" target="_blank">Cognifide</a>, available for free from <a href="http://trac.sitecore.net/SitecorePowershellConsole" target="_blank">Sitecore Shared Source</a> site.</p>
<img src="http://blog.najmanowicz.com/?ak_action=api_record_view&id=454&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://blog.najmanowicz.com/2011/11/24/extending-sitecore-ribbon-with-powershell-scripts/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Context PowerShell scripts for Sitecore</title>
		<link>http://blog.najmanowicz.com/2011/11/22/context-powershell-scripts-for-sitecore/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=context-powershell-scripts-for-sitecore</link>
		<comments>http://blog.najmanowicz.com/2011/11/22/context-powershell-scripts-for-sitecore/#comments</comments>
		<pubDate>Tue, 22 Nov 2011 13:34:14 +0000</pubDate>
		<dc:creator>Adam Najmanowicz</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.najmanowicz.com/?p=442</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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?</p>
<p>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.</p>
<p>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.</p>
<p><img style="background-image: none; border-right-width: 0px; margin: 3px auto 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="SqlManagementScripting" border="0" alt="SqlManagementScripting" src="http://blog.najmanowicz.com/wp-content/uploads/2011/11/SqlManagementScripting.png" width="590" height="209" /></p>
<p>Similarly but the other way around, with the PowerShell Console for Sitecore, you can attach scripts to the context menu in your item tree.</p>
<p><img style="background-image: none; border-right-width: 0px; margin: 3px auto 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="ContextScripts" border="0" alt="ContextScripts" src="http://blog.najmanowicz.com/wp-content/uploads/2011/11/ContextScripts.png" width="322" height="377" /></p>
<p><span id="more-442"></span>
<p>An execution of such script can be completely silent but you can also add a question before a script is executed:</p>
<p><a href="http://blog.najmanowicz.com/wp-content/uploads/2011/11/ContextScriptsConfirmation.png" rel="lightbox[442]" title="ContextScriptsConfirmation"><img style="background-image: none; border-right-width: 0px; margin: 3px auto 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="ContextScriptsConfirmation" border="0" alt="ContextScriptsConfirmation" src="http://blog.najmanowicz.com/wp-content/uploads/2011/11/ContextScriptsConfirmation_thumb.png" width="496" height="171" /></a></p>
<p>and&#160; if needed &#8211; show the results:</p>
<p><a href="http://blog.najmanowicz.com/wp-content/uploads/2011/11/ContextScriptsResults.png" rel="lightbox[442]" title="ContextScriptsResults"><img style="background-image: none; border-right-width: 0px; margin: 3px 3px 0px 7px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="ContextScriptsResults" border="0" alt="ContextScriptsResults" src="http://blog.najmanowicz.com/wp-content/uploads/2011/11/ContextScriptsResults_thumb.png" width="620" height="307" /></a></p>
<h2>Anatomy of a context script</h2>
<p>The PowerShell console comes with 2 sample scripts which for better or worse only demonstrate the potential of what can be done. The context part means that before executing your script the PowerShell environment location is set to your content item so <strong>Get-Item</strong> should yield the item you clicked on, whereas <strong>Get-ChildItem</strong> will get all of its children, potentially with their children if&#160; <strong>-recurse</strong> is used.</p>
<h3>1. Create a script</h3>
<p>Add a new script using the <strong><em>/sitecore/templates/Cognifide/PowerShell Script</em></strong> template in the core database. In my case I store my scripts within the <strong><em>/sitecore/content/Applications/PowerShell Console/Scripts</em></strong> branch but anywhere in the core database is fine really.</p>
<ul>
<li>Fill in the Script body part with your script. </li>
<li>If you want a warning/confirmation request to popup prior to the script execution provide it in the “pre-execution warning” box </li>
<li>and tick the checkbox if your script can generate output or you expect it to occasionally show errors. </li>
</ul>
<p align="center"><a href="http://blog.najmanowicz.com/wp-content/uploads/2011/11/ContextScriptBody1.png" rel="lightbox[442]" title="ContextScriptBody"><img style="background-image: none; border-right-width: 0px; margin: 3px 3px 0px 7px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="ContextScriptBody" border="0" alt="ContextScriptBody" src="http://blog.najmanowicz.com/wp-content/uploads/2011/11/ContextScriptBody_thumb1.png" width="300" height="207" /></a></p>
<h3>2. Create a menu item for your script</h3>
<p>Create a context menu item of template <strong><em>/sitecore/templates/System/Menus/Menu item</em></strong> within the <strong><em>/sitecore/content/Applications/Content Editor/Context Menues/Default/PowerShell/</em></strong> branch in the core database. If you have more than just a few scripts, a more elaborate structure might need to be created to group your scripts by functionality/purpose.</p>
<h3>3. Bind it to your script to the menu item</h3>
<p>Within the menu item you’ve just created edit the <strong><em>Message</em></strong> field and bind the script to it using the following pattern:</p>
<pre>item:executescript(id=$Target,script={1680E211-BD28-49BE-82FB-DA7232814C62},scriptDb=core)</pre>
<p>where the <strong><em>script</em></strong> guid is the ID of your script and the <strong><em>scriptDb</em></strong> is the database the script is located in.</p>
<p>Since this is a simple Sitecore command – similarly you can use the PowerShell functionality to expose your script on any ribbon or other kinds of menus!</p>
<p>That’s it really, and since you have pretty much all of the Sitecore API at your disposal you can hotfix a great deal of missing functionality without ever logging into Visual Studio, how is that not cool?!</p>
<p>On a final note… you might want to protect scripts that might create a heavy load on your site or do anything critical on your database from some users, but that’s a matter of simple permissions setting on your menu items.</p>
<h2 align="center"><a href="http://trac.sitecore.net/SitecorePowershellConsole" target="_blank">[Download &amp; Enjoy]</a></h2>
<p>All feedback appreciated!</p>
<img src="http://blog.najmanowicz.com/?ak_action=api_record_view&id=442&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://blog.najmanowicz.com/2011/11/22/context-powershell-scripts-for-sitecore/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Sample scripts for Sitecore PowerShell Console</title>
		<link>http://blog.najmanowicz.com/2011/11/18/sample-scripts-for-sitecore-powershell-console/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sample-scripts-for-sitecore-powershell-console</link>
		<comments>http://blog.najmanowicz.com/2011/11/18/sample-scripts-for-sitecore-powershell-console/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 12:24:25 +0000</pubDate>
		<dc:creator>Adam Najmanowicz</dc:creator>
				<category><![CDATA[.Net Framework]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Samples]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Sitecore]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Solution]]></category>
		<category><![CDATA[Web applications]]></category>

		<guid isPermaLink="false">http://blog.najmanowicz.com/?p=427</guid>
		<description><![CDATA[Find out about your configuration: List your available site providers. You will use the name provided in the &#8220;Name&#8221; column in place of where I use &#8220;cms&#8221; in the later samples. get-psdrive ` &#124; where-object { $_.Provider.ToString() -eq "CmsItemProvider"} ` &#124; format-table Name, Root Sample scripts for working with pages: For the same of brevity [...]]]></description>
			<content:encoded><![CDATA[<h2>Find out about your configuration:</h2>
<p style="margin-bottom: 10px;">List your available site providers. You will use the name provided in the &#8220;Name&#8221; column in place of where I use &#8220;cms&#8221; in the later samples.</p>
<pre class="ps1">get-psdrive `
  | where-object { $_.Provider.ToString() -eq "CmsItemProvider"} `
  | format-table Name, Root</pre>
<h2>Sample scripts for working with pages:</h2>
<p style="margin-bottom: 10px;">For the same of brevity I’m assuming your location is already somewhere within a Sitecore tree (e.g. you did something akin to <strong><em>cd master:\content</em></strong> prior to executing the following scripts.</p>
<p style="margin-bottom: 10px;">List all properties &amp; fields available for a particular page (including Sitecore properties defined in the item template).</p>
<pre class="ps1">get-childitem | get-member -memberType property*</pre>
<p style="margin-bottom: 10px;">List all items in the CMS of which template name contains &#8220;Article&#8221;</p>
<pre class="ps1">get-childitem -recurse `
  | where-object { $_.TemplateName -match "Article" } `
  | format-table DisplayName, Name, TemplateName</pre>
<p style="margin-bottom: 10px;">List all subitems and how many days ago were they modified</p>
<pre class="ps1">get-childitem -recurse `
  | format-table Name, `
  @{Label="Days since modified"; Expression={ `
  [datetime]::Now.Subtract([Sitecore.DateUtil]::IsoDateToDateTime($_.Updated)).Days} }</pre>
<p style="margin-bottom: 10px;">Delete all pages that have not been modified for the last 365 days.</p>
<pre class="ps1">get-childitem -recurse `
  | where-object {[datetime]::Now.Subtract([Sitecore.DateUtil]::IsoDateToDateTime($_.Updated)).Days -gt 365 } `
  | remove-item</pre>
<p style="margin-bottom: 10px;">List all items Updated over the last 24 hours and who changed them.</p>
<pre class="ps1">get-childitem -recurse `
  | where-object { [Sitecore.DateUtil]::IsoDateToDateTime($_.Updated) -gt [datetime]::Now.AddDays(-1) } `
  | format-table -property DisplayName, UpdatedBy, {$_.Paths.Path}</pre>
<p style="margin-bottom: 10px;">List all pages that have their &#8220;Text&#8221; field filled in.</p>
<pre class="ps1">get-childitem -recurse `
  | where-object { $_.Text -ne $null } `
  | format-table -property DisplayName, {$_.Paths.Path}</pre>
<p style="margin-bottom: 10px;">Make a nice reviewer&#8217;s comment on all pages with their &#8220;Text&#8221; property filled in.</p>
<pre class="ps1">get-childitem -recurse `
  | where-object { $_.Text -ne $null } `
  | foreach-object { $_.ReviewersComment = "Great job providing content!" }</pre>
<p style="margin-bottom: 10px;">Add a warning to the beginning of &#8220;Text&#8221; property for all pages that have not been saved for the last 180 days.</p>
<pre class="ps1">
get-childitem -recurse `
  | where-object {`
  [datetime]::Now.Subtract([Sitecore.DateUtil]::IsoDateToDateTime($_.Updated)).Days -ge 180 `
  -and $_.Text -ne $null }
  | foreach-object {$_.Text = "&lt;p style='color:red'&gt;Old content. Review pending!&lt;/p&gt;" + $_.Text }</pre>
<p style="margin-bottom: 10px;">Replace a string in a property on all pages with another string (in this sample &#8211; removing the warning the last sample added).</p>
<pre class="ps1">$old_content = "&lt;p style='color:red'&gt;Old content. Review pending!&lt;/p&gt;"
$new_content = "";
get-childitem -recurse `
  | where-object {$_.Text -match $old_content} `
  | foreach-object {$_.Text = $_.Text.Replace($old_content, $new_content) }</pre>
<p style="margin-bottom: 10px;">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.</p>
<pre class="ps1">get-childitem -recurse `
  | sort-object -property Updated -descending `
  | select-object -First 10 `
  | format-table -property DisplayName, UpdatedBy, Updated</pre>
<h2>Sample scripts for working with Media Library / files:</h2>
<p style="margin-bottom: 10px;">Removes all .xml files from the “Old Xml Files” in Media library.</p>
<pre class="ps1">cd "master:\media library\Old Xml Files"
get-childitem -recurse `
  | where-object { $_.Extension -match "xml" } `
  | remove-item</pre>
<p style="margin-bottom: 10px;">Copy all files from the &#8220;staging&#8221; folder to the &#8220;production&#8221; folder in Media Library.</p>
<p style="margin-bottom: 10px;">Copying files within media library is done as follows. This can also be done for items in the content branch.</p>
<pre class="ps1">copy-item "master:\media library\staging\*" "master:\media library\production\"</pre>
<img src="http://blog.najmanowicz.com/?ak_action=api_record_view&id=427&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://blog.najmanowicz.com/2011/11/18/sample-scripts-for-sitecore-powershell-console/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

