Exceptions in PowerShell

When scripting anything in PowerShell, you might find out that the exception handling in PowerShell V2 is not very extensive. I ran into a problem using the “New-SPSite” cmdlet for SharePoint 2010. The solution that I used for my problem can also be used for any other Cmdlet.

Running this cmdlet when the site collection does not yet exist, would give no problems. If a site collection already exists, and you try to create a new site collection using the same URL, you get a “not so user friendly” error.
image

The script I was creating was not just creating a site collection, so I would like to see just a message saying “The site collection could not be created.”.

Since I am still a PowerShell beginner, I was trying to find a way to accomplish this.
The first thing that came in mind, and I had used successfully before, was using Try{} Catch{] to see if a command executed correctly. In this case however, the command is execution just fine, but the result is not what you would want, so the Try{} Catch{} was not a solution.

To resolve this issue, I used the following “check” to see if the command had executed correctly, using an if statement.

#Check if the command I ran was executed correctly
if([bool](New-SPSite “http://yourdomain.com” –OwnerAlias “SA\Administrator” –ErrorAction SilentlyContinue) –Eq $false){Write-Host “The site collection could not be created” –fore red}

The parameter –ErrorAction SilentlyContinue suppresses the actual error, so the result will be clean. The suppressing of the error will only happen for this New-SPSite cmdlet, so it will not affect the rest of your script.
If you want to suppress ALL error messages (I don’t see a reason why anyone would want this), you can change the $ErrorActionPreference variable. The default value is “Continue”. Change the value to “SilentlyContinue” to suppress error messages in your PowerShell session.

$ErrorActionPreference = “SilentlyContinue”

Creating an error in SharePoint 2010

Every once in a while, I give a SharePoint 2010 training, where the main focus lies in the infrastructural background.
One of these aspects is the monitoring of SharePoint 2010 and how to manage it and troubleshoot the best way possible. To do this, I use the ULSViewer.

You would think that it is pretty easy to create an error, seeing as how often you get an “unexpected error” in SharePoint. To make things easier, I found this article by Todd Carter. He shows a way to create custom error pages.

This gave me the idea to use the bug he pointed out, to demonstrate the ULS viewer.
From here it is pretty straightforward.
I opened the ULS viewer to start scanning my ULS by pressing CTRL + U. The ULS Viewer will automatically find the location of the logs and will open it real-time.

Using the bug, I navigated to “http://yourdomain.com/_layouts/Error.aspx?ErrorText=Error for demo purposes.”. I have registered this domain in my local DNS file for demonstrating purposes.
This shows the following screen:

image

Using the ULS viewer, i filtered the log for correlation ID “fb134e8c-553b-47ff-9a5d-e81d329e10dd “.

Now, the log has been filtered only to see the error I had created!

image

Of course, in this case, the only message that is visible is the GET request for the error page, but it did the trick!

Export/Import SharePoint 2010 solutions using PowerShell (Part 3/3)

This last part will contain a script that will deploy the solutions to all available web applications. So you should only use this script if the solutions that are not deployed, have to be deployed on all SharePoint 2010 Web Applications.
Alternitavely, you can also change the script to only deploy the solution to 1 or more Web Applications.

Just to make sure, I Added a “Warning box”, which will display the information described above for people who had no time to read the piece of information.

#This script will deploy all added solutions to all web applications
Add-PSSnapin Microsoft.SharePoint.PowerShell

#Functions
function deploySolutions
{
    $Yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes"
    $No = New-Object System.Management.Automation.Host.ChoiceDescription "&No"
    $choices = [System.Management.Automation.Host.ChoiceDescription[]]($Yes,$No)
    $caption = ""
    $message = "Choosing YES will deploy ALL solutions available to ALL web applications, are you sure?"
    $result = $Host.UI.PromptForChoice($caption,$message,$choices,0)
   
    if($result -eq 0)
    {
        Get-SPSolution | ForEach-Object {If ($_.ContainsWebApplicationResource -eq $False) {Install-SPSolution -Identity $_ -GACDeployment} else {Install-SPSolution -Identity $_ -AllWebApplications -GACDeployment}}
    }
    elseif($result -eq 1)
    {
        Write-Host "you chose not to deploy the solution, press any key to exit" -fore red
        $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
}

deploySolutions

The output of the above script will look similar to this:

image
Improvements for all scripts posted are very welcome!.

Happy scripting!

Export/Import SharePoint 2010 solutions using PowerShell (Part 2/3)

Following up on the exporting of all solutions deployed in SharePoint 2010 in part 1, now it’s time to import these solutions to a different SharePoint 2010 farm.

Part 2 – Import all exported solutions to any SharePoint 2010 environment

In this part, we will cover how to add the solutions to another SharePoint 2010 farm. This is equal to using the “Add-SPSolution” command in PowerShell, only it does this for all solutions in a given directory.

Here is the script we will use:

#This script will add all solutions in the selected folder
Add-PSSnapin Microsoft.SharePoint.PowerShell

#Functions
function getPath
{
    #Get the directory that contains the solutions
    $inputPath = Read-Host "Enter the full path that contains the solutions (eg. C:\solutions)"
    return $inputPath
}

function addSolutions($importPath)
{
$counterItemsAdded = 0
Write-Host "Adding the solutions to the SharePoint environment" -fore green

#Check if specified path exists, if it does, add all solutions in the directory
if((Test-Path $importPath) -eq $True)
    {
    $items = Get-ChildItem $importPath | ?{$_.extension -eq ".cab" -or $_.extension -eq ".wsp"} #Gets all files that have the .cab or .wsp extension
   #The following line checks all currently installed solutions and adds these to $solutions
    $solutions = (Get-SPFarm).Solutions | Foreach-Object{$solnames += $_.name;} #Get all current SPSolutions
   
        foreach($item in $items)
        {
        #If the solution does not exist within the current environment
        if($solnames -notmatch $item.toString())
            {
                Add-SPSolution -LiteralPath $item.Fullname | out-null
                Write-Host "Imported $item" -fore green
                $counterItemsAdded += 1
            }
        else
            {       
                Write-Host "$item already exists on the SharePoint environment." -fore red
            }
        }
        #If at least 1 solution has been added
        if($counterItemsAdded -ge 1)
        {
        Write-Host "The solutions have been added`n" -fore green
        Write-Host "Remember, the solutions will not be available until you deploy them" -fore yellow
        }
        else
        {
        Write-Host "The specified directory didn’t contain any valid .WSP or .CAB files" -fore red
        }
    }
#If the current path does not exist, ask for the path again   
else   
    {
    Write-Host "Directory does not exist. `nPlease enter the path in the following format: C:\Solutions" -fore yellow
    addSolutions(getPath)
    }
}

Write-Host "This script will add all solutions in the specified directory to SharePoint 2010" -fore green

#Call functions
addSolutions(getPath)

The output of this script (when there are actually some valid .wsp files in the directory) will look something like this:

image

Like the output says, in order to use the solutions, you will have to deploy them first. You can do this manually, by using the PowerShell command “Install-SPSolution”, or you can go to part 3, where I created a script to do deploy ALL added solutions to your web applications.

Export/Import SharePoint 2010 solutions using PowerShell (Part 1/3)

When working with solutions in SharePoint 2010, it can be hard to track the location of your latest WSP’s. To resolve this, I created a script that will export all currently deployed solutions to your local hard drive.

Part 1 – Export all deployed solutions from the SharePoint 2010 environment

The following script can be copied into notepad and saved as a .ps1 file. Just execute the script to export the solutions. When you run the script, it will ask for an export location. This folder does not have to exist on your harddrive.

#Export all SharePoint 2010 solutions
Add-PSSnapin Microsoft.SharePoint.PowerShell

#This is the path that will be used to import/export the solutions.
$ExportPath = Read-Host "Enter the export location (eg. C:\Solutions). This directory will be created if it doesn’t exist"

function checkCreatePath($checkPath)
{
#Check if the path already exists
if((Test-Path $checkPath) -eq $False)
{
#if the path does not exist, it will be created
New-Item $checkPath -type Directory | out-null
Write-Host "Directory created" -fore green
}
else
{
#if the path does not exist, you will be notified
Write-Host "Directory already exists" -fore green
}
#Run the exportAllSolutions
exportAllSolutions($ExportPath)
}

function exportAllSolutions($path)
{
#The following line will export all solutions that are deployed in your current farm
(Get-SPFarm).Solutions | where{$_.Deployed -ne $null} | ForEach-Object{$solution = $path + "\" + $_.Name; $_.SolutionFile.SaveAs($solution); Write-Host "Exporting $solution"}
Write-Host "All solutions are exported to $exportPath, press any key to exit" -fore green
#The following line will wait for user input to exit the script
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}

checkCreatePath($ExportPath)

Running this script on a test environment, resulted in the following:
Export solutions using PowerShell

The directory C:\MySolutions now contains 11 solutions. In a live environment, you would now copy the folder with all the solutions to another SharePoint environment.

In part 2 I will share a script that will import these solutions into another SharePoint 2010 farm.