Navigate Up
Sign In
Supporters of Developer
Web

SharePoint: PowerShell for Developers - Part 1

Item is currently unrated. Press SHIFT+ENTER to rate this item.1 star selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+ESCAPE to leave rating submit mode.2 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.3 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.4 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.5 stars selected. Press SHIFT+ENTER to submit. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.

You may also be interested in: O'Reilly - SharePoint 2010 at Work

 

Editor's note: Contributor Adam Burcher is a SharePoint Developer and IT Admin working as a consultant for Mando Group. Follow him @sharepointbaker

This is the first of a series of articles looking at PowerShell and in particular showing some of the ways in which we can use PowerShell and extend it. For the most part I’m going to be focusing on how PowerShell can be used with SharePoint, but most of the concepts are the same no matter what you’re trying to script. Also, if you’re looking for a guide to some of the out of the box, then I’m afraid this series won’t spend a lot of time looking at them in any detail.

At this point if you’re not 100% sure on what PowerShell is, or what it does then I’d suggest a quick look online first!

Getting Started

Technically all you need to write a PowerShell script in is Notepad (as long as you can save it with a .ps1 extension), however just as you can technically write a website in Notepad, not many people recommend it! I personally like using PowerGUI, it has a good UI, inline console and some helpul intellisense. A quick search online will give you a number of alternatives which offer similar functionality. If you’re going to follow some of the demos in this series then any of the scripts which use SharePoint (either out of the box cmdlets or object model) will need to be run on a SharePoint server. Ideally this should be a developer environment so that you are able to run scripts and mess around without breaking any crucial systems. Something I always say is that PowerShell should be treated like production code. You wouldn’t (or shouldn’t) run a newly written piece of code directly on your production environment without having done some testing before hand. Apply the same rules to your PowerShell scripts, run them on a test or UAT environment first!

PowerShell vs C# – a brief overview?

If you’re comfortable writing C# code (whether for SharePoint or not) then turning that code into PowerShell is relatively straight-forward and a lot of the syntax between C# and PowerShell are familiar. We can also make use of .Net Libraries which means we’re treading familiar ground. Now there are some differences in some of the syntax that you need to be aware of and I’m going to take a look at just a few of these. This isn’t an exhaustive list, but it should help get you started.

Variables

One of the key differences between C# and PowerShell is that variables in PowerShell start with $, so for example (also notice no ; at the end of a line):

2012-05-22-PowerShellForDevs-Part01-01.jpg

Also, you do not always needs to include a data type when you’re declaring variables as PowerShell will infer the type based around what values are set. I tend to include a type definition when I’m writing functions and in cases where actually it makes reading the code easier and more maintainable. Something else to note is that when you assign a new value you can also change the data type – so for example this is valid in PowerShell:


$var = 123
$var.GetType()
$var = "ABC"
$var.GetType()

When this is run you will get both a Int32 and a String being outputted. However, if you try a similar script in C#, Visual Studio will actually throw up an error saying that you cannot convert a string to an integer. This is just something to bear in mind, if a variable inadvertantly gets assigned a different data type during execution it will cause problems and it won’t always be easy to spot.

Methods & Functions

Just like C# we can write methods (functions in PowerShell) which we can then call and reuse. In the next part of this series we’ll look at how you can reference and call out to functions in other ps1 files, but for now we’ll keep them all within the same one.

2012-05-22-PowerShellForDevs-Part01-02.jpg

Once a function has been declared we can call it in our script. Notice in the functions parameters I’ve included [string] which indicates its data type. Strictly speaking this isn’t required – the script will quite happily run without it. However, I prefer to include – you may not! Although we can access compiled code through PowerShell, it’s still a scripting language which means when you run through a script you cannot call a function until after it has been declared. If you’ve used some of the standard PowerShell cmdlet (like Get-SPSite etc) then custom functions follow a similar syntax:


DoSomething -myVar "Example" 

The same thinking behind when you create a new method in C# can typically be applied to when you should create functions in PowerShell.

Comparators

This is one the differences between C# and PowerShell which you need to remember. If you are doing comparisons: < > == etc then these take on a slightly different format in PowerShell:

2012-05-22-PowerShellForDevs-Part01-03.jpg

So if you were writing an ‘if’ statement it would look something like this:


 if ($myVar -eq "Example") { }

if ($anotherVar -gt 10) {}

Pipes

Pipes (‘|’) are a powerful command in PowerShell as it lets us pass data between functions. So you can say take the output of function 1 and apply function 2. Some common examples of this are if you want to filter the results or control what data is returned. For example, Get-SPWebApplication (returns all Web Applications) will automatically output the DisplayName and Url. However, if you want to display the Url and Id you can use a pipe and the select command:


Get-SPWebApplication | select Url, Id

Another example of how pipes can be used is to filter an output using the where (or ?) command, so for example:


Get-SPWebApplication | where { $_.Url -eq http://example}

In this example the results of Get-SPWebApplication are filtered so that only the Web Application with the Url of http://example is returned. These are just two examples of how pipes can be used and used correctly can be very useful. PowerShell itself comes with a large number of cmdlets that can be used in pipes – select and where are just two examples.

Writing a custom function example – Creating SharePoint Managed Accounts

Let’s take some of this and create a script. I want to write a script that will automate the creation of Managed Accounts within SharePoint, so rather than going through Central Admin I can run a script. Now SharePoint comes with a PowerShell cmdlet, New-SPManagedAccount which I could just call and pass in my various accounts. However, I don’t want my script to call New-SPManagedAccount if that account already exists, so what I can do is write a custom function that also makes use of Get-SPManagedAccount. I can check if a user exists first and then if it doesn’t I can call New-SPManagedAccount.

  1. Create a function, Add-ManagedAccount, passing ina username and password
  2. If user exists then output an message
  3. If user does not exist then create a new managed account

I’m going to walkthrough building up our custom function, showing what code needs writing. Initially we just have the function declaration for our method and we’re accepting two strings, one for the username and the other for the password.


 function Add-ManagedAccount ([string]$username, [string]$password) {
}

Now within our function we need to call Get-SPManagedAccount, but we’re going to use a pipe to provide a filter. We don’t want to return all managed accounts, only the one which matches our username parameter so we can add the following:


$managedAccount = Get-SPManagedAccount | ?{$_.UserName -eq $username}

Like the example we saw previously (in the pipe section) this line finds the managed account where the username equals the value that’s passed in and assigned it to the variable $managedAccount. The next step is to check whether or not the variable has a value, if it does then it means the account was found, if the variable isn’t set then it means that the user doesn’t exist and so needs creating.


 if ($managedAccount) {
    Write-Output "INFO - Managed Account $username exists"
}
else {
}

Here is another example of using the pipe, passing the output to Out-Null which hides the output of the New-SPManagedAccount which can be very useful when you’re writing your own scripts and want you’re own messages to be displayed. Now in my case I’m happy to include both my usernames and passwords in my script in plaintext (poor security I know, but it serves for this demo). The New-SPManagedAccount cmdlet takes a PSCredential variable which means we cannot just pass it a username and password. In order to do that we first have to call ConvertTo-SecureString which encrypts the password and then create out PSCredential object which can be passed through:


$securePwd = ConvertTo-SecureString $password -asPlainText -force
$accountCred = New-Object System.Management.Automation.PSCredential $username, $securePwd
New-SPManagedAccount -Credential $accountCred | out-null

Our final code looks like this and below the function is an example of how can be called:


function Add-ManagedAccount ([string]$username, [string]$password) {
 $managedAccount = Get-SPManagedAccount | ?{$_.UserName -eq $username}  
 if ($managedAccount) {   
     Write-Output "INFO - Managed Account $username exists"  
 }  
 else {   
     $securePwd = ConvertTo-SecureString $password -asPlainText -force    
     $accountCred = New-Object System.Management.Automation.PSCredential $username, $securePwd   
     New-SPManagedAccount -Credential $accountCred | out-null   
     Write-Output "INFO - Managed Account $username was created" 
 }
}

Add-ManagedAccount -username "TSB\spFarm" -password "examplepassword" 

I can save this script as a ps1 file and copy that to my environments to run. And this same basic approach can be used with a number of SharePoint cmdlets – New-SPWebApplication, New-SPSite etc.

For a first script that’s not bad, and hopefully you’ll be able to start rolling out some of your own. In the next post (coming soon) we’ll look at how we can start interacting with the SharePoint OM!

PS. If you’d like a sneak preview I have some slides and code examples that I put together for the SharePoint Saturday in Belgium where I went through some of these scripts. You can find the material here.

Categories: PowerShell; dev; C#; MOSS; WSS; 2010

Comments

Notify me of comments to this article

E-mail:
   

Add Comment

Title:

 
Comment:
Email:

   


Name:

 
Url: