Branding your SharePoint Sites

Branding your SharePoint Site and adding your custom masterpage, stylesheet, logo and favicon is fun and, thanks to Thomas Balkeståhl, its also rather simple.

Thomas has done a great job releasing a SharePoint 2010 Branding Project that helps you brand your SharePoint 2010 sites. And the best part: It’s free :)

Check it out Here

Rating 4.50 out of 5
[?]

SharePoint 2010

This post is part of the Second Wednesday Demo Session, Click here for more info about additional demo posts.

In a previous post we used Windows PowerShell to Create a Database, add a table and populate the table with alot of entries.

In the last part of this Demo we’ll use SharePoint 2010 to populate a List in SharePoint based on a Table in SQL and finally Script up alot of Computers based on a SharePoint List.
First let’s take a look at the SharePoint List.

The List contains three Columns that we will use: Title, Description and Create. Create in this example is a Yes/No column.

In a previous post we populated a Table in SQL with Computers. Let’s take a look at how we can read information from that list. The function below demonstrates how we can read data from a table.


function Get-SQLComputer {

  $Connection = New-Object System.Data.SqlClient.SqlConnection
  $Connection.ConnectionString = "server=SQL01;database=TestDB;trusted_connection=true;"

  # open Connection
  $Connection.Open()
  $Command = New-Object System.Data.SQLClient.SQLCommand
  $Command.Connection = $Connection
  # Add Query
  $Command.CommandText = "SELECT * FROM Computers"
  # read from table
  $Reader = $Command.ExecuteReader()
  $Counter = $Reader.FieldCount
  # itterate each row
  while ($Reader.Read()) {
      $SQLObject = @{}
      for ($i = 0; $i -lt $Counter; $i++) {
      $SQLObject.Add(
        $Reader.GetName($i),
        $Reader.GetValue($i)
      );
    }
    # return hashTable
    $SQLObject
  }
  # Close Connection
  $Connection.Close()
}

The function above returns the rows in the table. Now let’s add them to our custom SHarePoint list.

Note that the function above doesn’t require any input. If you write a function that takes input when performing a query you should consider using parameterized queries to avoid possible injections. here’s a short example:


function Get-SQL([string]$ComputerName) {

  $Connection = New-Object System.Data.SqlClient.SqlConnection
  $Connection.ConnectionString = "server=SQL01;database=TestDB;trusted_connection=true;"

  $Connection.Open()
  $Command = New-Object System.Data.SQLClient.SQLCommand
  $Command.Connection = $Connection

  $Command.CommandText = "SELECT * FROM Computers WHERE Computer = @ComputerName"

  # These two lines are added to avoid injections
  $SQLParameter = New-Object System.Data.SqlClient.SqlParameter("@ComputerName", $ComputerName)
  [void]$command.Parameters.Add($SQLParameter)

  $Reader = $Command.ExecuteReader()
  $Counter = $Reader.FieldCount

  while ($Reader.Read()) {
      $SQLObject = @{}
      for ($i = 0; $i -lt $Counter; $i++) {
      $SQLObject.Add(
        $Reader.GetName($i),
        $Reader.GetValue($i)
      );
    }

    $SQLObject
  }

  $Connection.Close()
}

First we use Add-PSSNapin to add the SharePoint 2010 CmdLets.


PS > Add-PSSNapin Microsoft.SharePoint.PowerShell

If your not running in sta mode, set the threadoption to “ReuseThread”.


PS > $host.Runspace.ThreadOptions = "ReuseThread"

Next we use Get-SPWeb to return a specific Site.


PS > $spWeb = Get-SPWeb http://SP01

Now we get the “Computer” list using the GetList() method.


PS > $spList = $spWeb.GetList("/Lists/Computers")

The spList has a method, AddItem(), which we can use to add a new Item in the SharePoint List. the example below demonstartes how we use the Get-SQLComputer function
to add the computers from the SQL table to a list in SharePoint 2010.


PS > Get-SQLComputer | ForEach {
>> $item = $spList.AddItem()
>> $item["Title"] = $($_.Computer).TrimEnd()
>> $item["Description"] = $($_.Description).TrimEnd()
>> $item.Update()
>> }

Finally we dispose of the spWeb object.


PS > $spWeb.Dispose()

If we take a look at the list now, the Computers are added.

Finally, let’s create some of the computers in Active-Directory. The SharePoint List had a Yes/No Column named Create. Let’s only create computers where the field is set to Yes.

In this example I’ve checked the Create filed for: DT001, DT003 and DT005. Let’s see how we can retrieve does specific items from SharePoint 2010 wqithout retrieving the whole ListItem Collection.
First we get the specific list.


PS > $spWeb = Get-SPWeb http://SP01
PS > $spList = $spWeb.GetList("/Lists/Computers")

The spList contains a property, ItemCount, that show us how many ListItems that are in the list.


PS > $spList.ItemCount

202

The spList also contains a property, Items, that returns all items in the list. Note that this can consume alot of unnecesary memory if your working with large lists so a better way of retrieving listitems is by using a CAML query.
In this example we only want listItems where Create equals Yes. Here’s an example on how to write such a query.


PS > $spQuery = New-Object Microsoft.SharePoint.SPQuery;
PS > $query = "<Where><Eq><FieldRef Name='Create' /><Value Type='Boolean'>1</Value></Eq></Where>"
PS > $spQuery.Query = $query

An easy way of getting your CAML queries correct is by using a CAML query builder.

Now we can Get the specific listItems using the GetItems() method and the spQuery object as input.


PS > $listItems = $spList.GetItems($spQuery)

If we count the number of listItems in the ListItem Collection we’ll see that it only contains 3 items.


PS > $listItems.Count

3

We can use the Select-Object cmdlet to Select the properties that we want to work with.


PS > $listItems | Select-Object @{Name="Name";Expression={$_.Title}},
>> @{Name="Description";Expression={$_["Description"]}}

Name                  Description
----                  -----------
DT001                 Added Using PowerShell
DT003                 Added Using PowerShell
DT005                 Added Using PowerShell

Finally, let’s go ahead and create the computers in Active Directory. In this example well start a Rmote background job that does the work for us.


PS > $computers = $listItems | Select-Object @{Name="Name";Expression={$_.Title}},
>> @{Name="Description";Expression={$_["Description"]}}
>> Invoke-Command -ComputerName DC01 -ScriptBlock {
>>   Import-Module ActiveDirectory
>>   $args | Foreach {
>>     New-ADComputer -Name $($_.Name) -Description $($_.Description) -Path "OU=LabCenter,DC=PowerShell,DC=nu"
>>   }
>> } -ArgumentList $computers -AsJob
>>

Id              Name            State      HasMoreData     Location             Command
--              ----            -----      -----------     --------             -------
7               Job7            Running    True            dc01                  ...

When the job completes the Computers are created in Active Directory

Rating 4.00 out of 5
[?]

Adding Permission Levels in SharePoint 2010 using PowerShell

In SharePoint 2010 you can manage what a User or Group can do by granting permissions to a User or Group.
SharePoint 2010 shippes with a couple of standard permission such as: Full Control, Design, Contribute and Read.
But how do you create your own Permission Levels?

Say you want a user to be able to View Pages and Lists, Download Documents and Update List Items but not Create or Delete List Items.

To achieve this, we have to create a custom Role Definition. First we return a Site using the Get-SPWeb cmdlet.


PS > $spWeb = Get-SPWeb http://SP2010

Next we Store an instance of Microsoft.SharePoint.SPRoleDefinition in a variable and set the Name and Description properties.


PS > $spRoleDefinition = New-Object Microsoft.SharePoint.SPRoleDefinition
PS > $spRoleDefinition.Name = "Custom"
PS > $spRoleDefinition.Description = "Can Create and Modify Items, Not Delete"

Next we want to add specific BasePermissions, but before adding them let’s see what kind of permissions we can add by enumerating Microsoft.SharePoint.SPBasePermissions.


PS > [System.Enum]::GetNames("Microsoft.SharePoint.SPBasePermissions")

EmptyMask
ViewListItems
AddListItems
EditListItems
DeleteListItems
ApproveItems
OpenItems
ViewVersions
DeleteVersions
CancelCheckout
ManagePersonalViews
ManageLists
ViewFormPages
Open
ViewPages
AddAndCustomizePages
ApplyThemeAndBorder
ApplyStyleSheets
ViewUsageData
CreateSSCSite
ManageSubwebs
CreateGroups
ManagePermissions
BrowseDirectories
BrowseUserInfo
AddDelPrivateWebParts
UpdatePersonalWebParts
ManageWeb
UseClientIntegration
UseRemoteAPIs
ManageAlerts
CreateAlerts
EditMyUserInfo
EnumeratePermissions
FullMask

Pretty cool!. In our Case we want to add the same Base Permissions as the “Read” permission level has, which are: ViewListItems, OpenItems, ViewVersions, ViewFormPages, Open, ViewPages, CreateSSCSite, BrowseUserInfo, UseClientIntegration, UseRemoteAPIs, CreateAlerts.
We also want to add additional an additional permission: EditListItems. So that the Users can Edit Items (but not create or delete Items).


PS > $spRoleDefinition.BasePermissions = 
>> "ViewListItems, OpenItems, ViewVersions,
>> ViewFormPages, Open, ViewPages, CreateSSCSite,
>> BrowseUserInfo, UseClientIntegration,
>> UseRemoteAPIs, CreateAlerts,EditListItems"

Finally, we add our custom Rolde Definition to our Site as demonstrated below:

   
PS > $spweb.RoleDefinitions.Add($spRoleDefinition)

Now we can simply add Grant Users or Groups our new Custom permission as shown below.

When the User or Group logs into SharePoint 2010 he/she will be able to view content, Update List Items but not Create or Delete List Items.

Rating 3.80 out of 5
[?]

SEF 2010

First day of SEF 2010 is coming to an end and there have been some great sessions today and alot of great speakers.

I did my session on PowerShell & SharePoint 2010, demonstrating some examples on scripting your SharePoint 2010 environment and added some examples from my and Mattias Karlsson’s book: PowerShell for SharePoint 2010 Administrators.

The first example demonstrated how to automate a SharePoint 2010 installation with just a few basic cmdlets.


# Converting password strings to secure strings
PS > $securePassword = ConvertTo-SecureString `
>> -String "Password1" -AsPlainText -Force

PS > $securePassPhrase = ConvertTo-SecureString `
>> -String "Password1" -AsPlainText -Force

# Creating a PSCredential object
$psCredentials = New-Object -TypeName System.Management.Automation.PSCredential `
>> -ArgumentList "powershell\administrator", $securePassword

# New Configuration Database
PS > New-SPConfigurationDatabase -DatabaseName "ConfigDB" `
>> -DatabaseServer "SP2010" -AdministrationContentDatabaseName "Admin_ContentDB" `
>> -Passphrase $securePassPhrase -FarmCredentials $psCredentials

# Install help files
PS > Install-SPHelpCollection -All

# Install services
PS > Install-SPService

# Install Features
PS > Install-SPFeature -AllExistingFeatures

# Create a new Central Administration
PS > New-SPCentralAdministration -Port 5057 -WindowsAuthProvider "NTLM"

# Copy shared application data
PS > Install-SPApplicationContent

Next I demonstrated how to setup a new WebApplication using Windows PowerShell.


PS > $credentials = Get-Credential
PS > New-SPManagedAccount -Credential $credentials
PS > $waName = "Collaboration Area"
PS > $databaseName = "SharePoint_Workspace_ContentDB_01"
PS > $internalHostHeader = "SP2010"
PS > $internalUrl = "http://SP2010"
PS > $port = "80"
PS > $appPool = "SharePoint_Workspaces_applicationPool"
PS > $appPoolUser = Get-SPManagedAccount -Identity "powershell\managedaccount”

PS > New-SPWebApplication -Name $waName -ApplicationPool $appPool `
>> -ApplicationPoolAccount $appPoolUser -URL $internalUrl `
>> -HostHeader $internalHostHeader -Port $port -DatabaseName $databaseName

After the Web Application is setup I moved on to Site Collections. It’s actually real simple to create a new Site Collection using Windows PowerShell.


PS > New-SPSite -Url http://SP2010 -Template "STS#0" -OwnerAlias "powershell\administrator" `
>> -Name "Collaboration Area" -Description "Jolly Good"

Next I demonstrated some of the functions included in “PowerShell For SharePoint 2010 Administrators” that help you get and set the theme on a site.


PS > Get-SPTheme http://SP2010

Theme       : Mission
Type        : GalleryTheme
RelativeUrl : /_catalogs/theme/Themed/EDE932A5/theme.thmx
Description : This theme has Black text on a White background in the content ar
              ea, Dark Yellow text on a Tan background in the navigation area,
              accents in Dark Green, Gold, Dark Red, Red, Gold, Brown, and Dark
               Green hyperlinks.

In the example above the Get-SPTheme function is used. The function displays the current theme on a Site. To display the available Themes – use the Get-SPThemeName function.


PS > Get-SPThemeName http://SP2010

Name
----
Azure
Berry
Bittersweet
Cay
Classic
Construct
Convention
Felt
Graham
Grapello
Laminate
Mission
Modern Rose
Municipal
Pinnate
Ricasso
Summer
Vantage
Viewpoint
Yoshi

Finally, to set a Theme, simply use the Set-SPTheme function.


PS > Set-SPTheme -url http://SP2010 -theme Ricasso

Next, I demonstrated how to create a List in SharePoint 2010 using the New-SPList function. First I demonstrated the -showTemplate switch that displays the available List Templates.


PS > New-SPList -url http://SP2010 -showTemplate

Template Name                 Type
-------------                 ----
Document Library              101
Form Library                  115
Wiki Page Library             119
Picture Library               109
Links                         103
Announcements                 104
Contacts                      105
Calendar                      106
Discussion Board              108
Tasks                         107
Project Tasks                 150
Issue Tracking                1100
Custom List                   100
Custom List in Datasheet View 120
External List                 600
Survey                        102
Data Connection Library       130
Converted Forms               10102
Asset Library                 851
Status List                   432
Data Sources                  110
No Code Public Workflows      122
Custom Workflow Process       118
Slide Library                 2100
Workflow History              140
Report Library                433
No Code Workflows             117

Next I used the Announcements Template to create a New List.


PS > New-SPList -url http://SP2010 -name "My Announcements" -description "Coolt" -template 104

I also demonstrated how to add a List to the QuickLaunch using PowerShell.


PS > $spList = Get-SPList -url "http://SP2010/Lists/My Announcements"
PS > $spList.OnQuickLaunch = $true
PS > $spList.Update()

In the last exmaple I demonstrated how to Add a List Item to an Announcements list in SharePoint 2010 using Windows PowerShell.


PS > $item = $spList.AddItem()
PS > $item["Title"] = "Nyhet"
PS > $item["Body"] = "<h2>SEF2010</h2>"
PS > $item["Expires"] = $((Get-Date).AddDays(50))
PS > $item.Update()

I also added a short demo on how you can monitor a process (Calc.exe) and add a new List Item if the process starts. Here’s that example.


PS > do { 
>>  if(Get-Process | Where { $_.ProcessName -eq "Calc" }) { 
>>   $programStarted = $true
>>   $calc = Get-Process | Where { $_.ProcessName -eq "Calc" }
>>   $spList = Get-SPList -url "http://SP2010/Lists/My Announcements"
>>   $item = $spList.AddItem()
>>   $item["Title"] = $calc.Name
>>   $item["Body"] = [string]::Join("`n",$($calc | 
>>    Select-Object -Property Name, Description, ProductVersion, Path, Company | 
>>    ConvertTo-Html -As List))
>>   $item["Expires"] = $((Get-Date).AddDays(50))
>>   $item.Update()
>>  }
>> } while ($programStarted -ne $true)

Click here to download the PowerPoint Presentation.

Rating 4.00 out of 5
[?]

SharePoint & PowerShell Week @ScriptingGuys

Recently I wrote a couple of posts for ScriptingGuys, describing how to use SharePoint 2010 and PowerShell. Many of the examples from the post are from my and Mattias Karlsson’s book: PowerShell for SharePoint 2010 Administrators, which will be released October 29, this year.

You can check out the SharePoint & PowerShell Week posts here:

Get Started Managing SharePoint 2010 with PowerShell Cmdlets

Use SharePoint 2010 PowerShell Cmdlets to Get and Manage Sites

Use PowerShell to Manage Lists, Views, and Items in SharePoint

Use PowerShell Cmdlets to Manage SharePoint Document Libraries

Rating 2.00 out of 5
[?]