Hi,

There are few months I didn’t blog, and I am really sorry about that. The main reason for this is that I worked in SharePoint Engineering team for the last 6 months. I’ll give more details on that in a later post.

Among the things I learned there, I dramatically improved my knowledge and expertise in Windows PowerShell :-) .

One of the direct use of this knowledge can be applied to the scripts I published here few months ago. This post was viewed by more than 5,000 visitors, so a little improvement of these may be useful for some of you.

As you’ve seen, the “code practice” of these scripts is bad: a lot of redundancy, and no real flexibility. Let’s improve this:

- We’ll use the “dot sourcing” feature of Windows PowerShell:
You can load a script during the execution of another script, without derivation of the execution flow. What is the interest? You can load “parameters or settings” scripts in the “execution” scripts. In fact that’s pretty, pretty cool, and here’s how to do it

First we create one Windows PowerShell script that will hold all the settings and parameters. For SharePoint 2010, it looks like this

# SharePoint  Services variables list
$SQLSvc = "MSSQLSERVER","SQLWriter","SQLSERVERAGENT"
$IISSvc = "W3SVC"
$SPSvc = "SPTimerV4","DCLoadBalancer14", . . . . . 
$SPSearchSvc = "OSearch14","SPSearch4"

- Name and save it as desired (let’s say “settings.ps1”)

- Then, we’ll add to this SAME file the functions we use in the scripts:
- Windows PowerShell functions are structured like this: Function Name {Param([type]$parameter) Process { do something  }  }

- Here is an example of function:

    Function Start-SP2010
    {
        Param([string]$svc)
        Process
        {
            $servicePrior = get-service $svc
            "$svc is " + $servicePrior.status + " and will be Started"
            Start-Service $svc
            $serviceAfter = get-service $svc
            "$svc is now " + $serviceAfter.status
        }
    }

Add this code to the “settings & parameters” file and save it

Let’s now dot source this file and use it:

  • in the same folder that the one you stored the settings script, create a “Start-SP2010.ps1” file/script

  • Place in this file the following kind of “code”:

    Cls
    # Library loading
    Push-Location $PWD
    . .\Settings.ps1
    # Start local SQL Services
    "Starting Local SQL Services"
    $SQLSvc | ForEach-Object {Start-SP2010($_) }
    "=> Local SQL Services Started";" "
    # Start IIS
    .....

The key here is line 4: this is a dot, a space, a dot, a backslash, the settings.ps1 file created earlier.

That’s what we call dot sourcing a script. Once dot sourced, you can use any functions or variable from this script in another one.

The big advantage of that: you need to add or remove a Service? Just change the String pipe of the service and you’re done.

I attach the full set of scripts to this post (set to manual start, start & stop).

Enjoy

< Emmanuel />