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.

I have gathered some literature available for free about the topic of PowerShell in general you might want to read, 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.

A great deal of this post is a port of my older post 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.   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 Sitecore
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 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 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.

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

How to get help

Give a man a fish and you feed him for a day. Teach a man to fish and you feed him for a lifetime.

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.

To discover commandlet’s syntax you can use something like:

Get-Help Get-Item –Full
 
Get-Help ForEach-Object –Verbose

You can learn more about the help system by being slightly recursive Smile

Get-Help Get-Help –Full

There is a lot of discoverability within the environment. For example to learn about commandlets available to you you can try experimenting with these:

Get-Command -CommandType Cmdlet
 
Get-Command Get-*

You can discover what capabilities an object you got in pipeline possesses by using Get-Member e.g.:

Get-Item master:\ | Get-Member

And here go the Sitecore specific tips

How to work with items

To switch to the desired database item you would use the following:

cd master:\
 
cd core:\content\Applications

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:

cd master:\
Get-Item .

How to get Current Item

To get the page for the location you’re in you can use:

Get-Item .

How to get Current Page’s children

To get the children of the page you’re currently in:

Get-ChildItem

To get the children of the page you’re currently in and all of its children children (whole branch):

Get-ChildItem –recurse

How to Modify an item

Get-Item . | ForEach-Object { $_.Text = “<p>Hello World</p>” }

or in short:

Get-Item . |% { $_.Text = “<p>Hello World</p>” }

How to restart the application

To restart the application use the following command:

Restart-Application

How to get system properties and environment variables

Some more important variables are mapped onto the PowerShell variables by the plugin. Notable variables (value depending on your server configuration):

Name Sample value
$AppPath C:\inetpub\wwwroot\CognifideShowcase\
$AppVPath / (app virtual folder)
$tempPath C:\Windows\TEMP
$tmpPath C:\Windows\TEMP
$me sitecore\admin

You can list all PowerShell variables by using:

Get-Variable *

Additionally you can list all environment variables by using:

[System.Environment]::GetEnvironmentVariables()

and get the value of a specific variable with e.g.:

[System.Environment]::GetEnvironmentVariable("ComputerName")

PowerShell Language and environment specific tips

How to Insert Comments

To insert a comment, use the pound sign (#):

# This is a comment, not a line to be run.

How to Insert Line Breaks

To insert a line break into a Windows PowerShell script use the backtick (`) :

$b = `
"This is a continuation of the line."

You can also break a line at the pipe separator (|) character (assuming your line uses the pipeline):

Get-ChildItem C:\Scripts |
Sort-Object Length –Descending

How to Create Multi-Command Lines

To put multiple commands on a single line, separate those commands using a semicolon:

$a = 1,2,3,4,5; $b = $a[2]; $b

Hint. This script writes-out the value of $b which is 3

How to Make Comparisons

Windows PowerShell cmdlets (like Where-Object) use a special set of comparison operators, including those shown in the following table.

Each of these operators can be made case sensitive by adding a c immediately after the hyphen. For example, -ceq represents the case-sensitive equals operator; -clt is the case-sensitive less than operator.

-lt Less than
-le Less than or equal to
-gt Greater than
-ge Greater than or equal to
-eq Equal to
-ne Not equal to
-like Like (uses wildcards for matching)
-notlike Not like (uses wildcards for matching)

How to Read a Text File

To read the contents of a text file into a variable, call the Get-Content cmdlet followed by the path to the text file:

$a = Get-Content C:\Scripts\Test.txt

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:

$a[0]

This command echoes back the last line in $a:

$a[-1]

Bonus. To determine the number of lines, words, and characters in a text file use this command:

Get-Content c:\scripts\test.txt |
measure-object -line -word -character

How to Write to a Text File

To save data to a text file use the Out-File cmdlet:

Get-Item . | Out-File C:\Scripts\Test.txt

To append data to an existing file, add the –append parameter:

Get-Item . | Out-File C:\Scripts\Test.txt –append

Attention. Unlike in the regular Windows PowerShell console you cannot use the MS-DOS redirection characters (> for write, >> for append) when using Sitecore hosted PowerShell.

Another option is to use the Export-CSV cmdlet to save data as a comma-separated-values file:

Get-Item . | Export-CSV C:\Scripts\Test.txt

More tips coming soon… In the mean time please download the fresh version of the plugin with the latest improvements:

[Download & Enjoy]

All feedback appreciated!

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



This entry (Permalink) was posted on Wednesday, January 11th, 2012 at 9:36 pm and is filed under Code Samples, Downloadable, PowerShell, Sitecore, Software Development, Solution, Web applications. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response , or trackback from your own site.