Comments

Any seasoned developer will tell you that it is critical to document your code. This is valuable for many reasons. Documenting code helps

  • Make code readable
  • Help others understand what your script is doing
  • Helps you remember what you were thinking in case you need to refactor or modify your scripts

It can take quite a bit of time to read scripts to understand what is going on. Comments are your best way of shorting this process. In PowerShell, comments are specified by using the # symbol. Here are a couple of examples.

# SharePoint and PowerShell work great together

# Comments help make your code readable

Variables

In all programing and scripting languages, storage locations are needed to hold data so that it can be accessed at a later time. These locations are referred to as variables. In PowerShell, variables come in a variety of sorts. Variables hold a variety of data types much like the columns in a SharePoint list. We will examine some of these data types in a few moments, but prior to that, it is important that you understand how variables work and how you can use them in PowerShell.

Variables in PowerShell are designated with a dollar sign. An example of a variable that would store something like your name would look like this:

$name

The actual variable is ‘name’, the ‘$’ in front of it simply lets you know that it is a variable. Variables are used for a variety of things. You can use them to store values or you can use them to store references to objects. We will explain what I mean by objects in an upcoming chapter, but for right now, it is important that you know that a variable is an essential building block for a PowerShell script. Let’s take a look at some other examples.

$age = 18

$Is18OrOlder = True

$spHost = $host.RawUI.UI

In the examples above, you will see three different kinds of variables. Each variable begins is marked with a dollar sign. When we open up the IDE in a moment, this will become very clear why this is important. The name of variables can contain letters, numbers, spaces, or special characters. There are several accepted naming conventions that you may adopt. While variables may contain spaces, the use of spaces would require the variable name to be enclosed in parenthesis. Here are a few examples.

${SharePoint Site Name} = “Home”

${Content Database} = “WSS_Content”

So while these names will work in PowerShell, it is more common to see variables expressed using camel case. Camel case is a naming convention that has the first word lower cased, and the first letter of each additional word capitalized. The example above would look like the following:

$sharePointSiteName = “Home”

$contentDatabase = “WSS_Content”

Another common naming convention is the use of Hungarian Notation. In this notation, the variable has a prefix of the object type. We haven’t yet covered data types, but I will to give a brief example, take a look at the following lines.

$strSharePointSiteName = “Home”

$intAge = “18”

The prefix of “str” is telling the person reading the line of code that this variable is intended to be a string. The second example introduces “int”, which is common for integers. Typically, you use the first three letters of the data type as the prefix. It is important to note that just because a variable begins with “str”, doesn’t necessarily mean that it contains a string.

All of our examples up to this point have implicitly declared variables. This means that no data type was assigned to the variable. PowerShell uses an Adaptive Type System on implicitly declared variables. To examine this in detail, look at the following example.

Figure 1.1

Create a new variable named $strTopic and set it to “PowerShell”. We examine the type of data by checking to see if the variable “-is” a “[string]”. PowerShell returns “True”.

We now run the same test to see if the value is an integer and get a return value of “False”.

Once we assign $strTopic to a number, these tests actually reverse. PowerShell has converted the data type of $strTopic to an integer.

This can lead to confusion later on. The answer to this dilemma is the use of explicitly defined types.

Figure 1.2

In this example, we explicitly declare $strTopic as a [string]. This is done by leading the variable with the desired type. We assign the variable to a string just as we did before. This time, when we change the value to “0”, notice that the type remains a string and does not change to an integer.

We now take this exercise one step further.

Figure 1.3

We explicitly declare the variable $intAge as an integer. Assigning a string to this variable produces an error.

Cannot convert value “PowerShell” to type “System.Int32”. Error: “Input string was not in a correct format.”

As you see, this is extremely powerful if you want to maintain the integrity of your variables. Explicit declaration offers another advantage of its counterpart. It is actually faster performance wise, for you to define the data types explicitly rather than PowerShell handing this behind the scenes. This not only holds true in PowerShell, you will find this benefit is other languages as well. With that being said, I would also recommend that you name your variables in such a way that you know what type of data they hold. This would remove the need to guess down the road. You will be surprised that this is easy to forget if you are looking at a long script.

Thus far, we have examined the string and the integer types. Some of the other types that are available are listed in the grid below.

Data Type

Description

string Fixed-length string of Unicode characters
char A Unicode 16-bit character
byte An 8-bit unsigned character
int 32-bit signed integer
long 64-bit signed integer
bool Boolean True/False value
decimal A 128-bit decimal value
single Single-precision 32-bit floating point number
double Double-precision 64-bit floating point number
DateTime Date and Time
array An array of values

 

You can combine PowerShell statements on the same line by using the semi-colon. If you are coming from a development language similar to C# or Java, then this concept will be easy to grasp. We will now combine the previous example onto one line.

[string] $sharePointSiteName = “Home”; [string] $contentDatabase =”WSS_Content”

Open up a fresh SharePoint 2010 Management Shell window and type the following lines of code.

[int] $intNum1 = 5

[int] $intNum2 = 6

[int] $sum = $intNum1 + $intNum2

$sum

Figure 1.4

In this example, we assign a value to $intNum1 and $intNum2. We then add the value and store it in the variable $sum. If we type only the variable name, we can see the value that it contains. PowerShell offers a cmdlet for output values. Type Write-Output $sum into the shell window to see how this works. In the screen shot provided, notice that there is another example. Here we use echo $sum to review the value of our variable as well. Echo is an alias in PowerShell that maps to the Write-Output cmdlet. We will discuss aliases in more detail in the next chapter.

PowerShell offers you greater control over your variables by offering a cmdlet called Set-Variable. Type the following into your shell environment:

Get-Help Set-Variable

Figure 1.5

Using the Set-Variable, you are not only able to assign a value to the variable, but you also have the opportunity to set a description, scope, and other options.

It is also important to note, that if you are using the variable cmdlets, it is not nessecary to use the dollar sign. Type the following in the SharePoint 2010 Management Shell:

Set-Variable intNum 14

Write-Output intNum

Write-Output $intNum

Get-Variable intNum

Figure 1.6

You will notice that when you try to send the value of intNum using Write-Output to the host without the dollar sign, it actually sends the text ‘intNum’. You can use Get-Variable without the dollar sign to retrieve the value as indicated in figure 1.x.

The Set-Variable cmdlet has a little more to offer than just assigning a variable to a variable. To look deeper into this cmdlet, we will examine it through help alias or the Get-Help cmdlet


Figure 1.7

Notice the syntax section:

Set-Variable [-Name] <string[]> [[-Value] <object>] [-Description <string>] [-Exclude <string[]>] [-Force] [-Include <string[]>] [-Option {None|Read Only|Constant|Private|AllScope}] [-PassThru] [-Scope <string>] [-Visibility {Public|Private} ] [-Confirm] [-WhatIf] [<CommonParameters>]

There are a couple of items to point out. Using the Set-Variable allows you to associate a description with each variable. We also have the ability to set a scope and specify wither or not we will allow the variable to be read-only or constant.

Read-Only variables cannot be changed. You will need to either close the shell session you are working in or use the Remove-Variable cmdlet (or del alias), and recreate it.

If you create a variable as a constant, you will only be able to remove it by closing your current session. You are not allowed to delete a constant variable.

Throughout chapter, we have added quite a number of variables to our shell session. It may be difficult for you to remember which ones you have used and the values that were assigned to them. PowerShell offers a cmd-let that helps us with just that: Get-ChildItem. Get-Childitems gets items in one or more locations. In order to use it, you must know where the variables are stored. When you create a variable it gets stored with in a location called ‘variable:’, which is very similar to a drive with a colon after. To help you remember how to access the child items, PowerShell gives us a pre-defined alias of dir.

Armed with this new information, type the following into the shell window:

dir variable:


Figure 1.8

You will receive output similar to the illustration above. Here you will notice that there are a lot more variables that you have defined. These are referred to as Automatic Variables. We will discuss Automatic Variables in the next section.

In the previous examples, we created a number of variables that began with ‘int’. To view only these variables, type the following:

dir variable:int*

Figure 1.9

To filter out ‘intAge’, you can type the following:

dir variable:int* -exclude *Age

Figure 1.10

 

Automatic Variables

Automatic Variables are variables that are created by PowerShell that is used by the environment. To see a list of these variables, type the following into a new shell session window.

Dir variable: |sort-object Name|format-table Name, Description –wrap –autosize

 

Figure 1.11

You can find out more about Automatic Variables by typing the following:

Get-Help about_Automatic_Variables

Environmental Variables

While Automatic Variables are only visible within PowerShell, Environmental Variables are visible to other application running in a Window environment. Add the following line of code to your shell window:

dir env:

Figure 1.12

You will see from the results of the search, that these variables are extremely valuable. You can either modify an Environmental Variable for the current session or on the operating system itself.

To change an environmental variable inside your current session, simply assign the new value like you normally would. If you close the session and reopen it, you will see that the value is reverted back to its original state. If you need to make a modification that is visible to other applications, you will need to modify the variable using a .NET method. You can make these modifications either at the user level or the machine level.

$strOldValue = [environment]::GetEnvironmentvariable(“Path”,”User”)

$strNewValue = “;c:BlobCache”

[environment]::SetEnvironmentVariable(“Path”,$strNewValue,”User”)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s