Tag Archives: PowerShell

Using PowerShell to register SPGuidance diagnostic areas

The SPGuidance package delivers a set of components to ease certain administration tasks with SP 2010, for example logging.

It hooks in to the built-in SharePoint logging functionality and exposes a set of classes to easily log your own events in the event log, ULS logs or any custom log sources, like a database.

If one would look into this model, you will find that a diagnostic area corresponds to an event source in the event logs. For instance, if I register a diagnostic area called Boom.MyCustomApplication, the event source mentioned in the logs would read the same. This allows support engineers to easily track the source of the event and act accordingly.

However, although the diagnostic area corresponds to the event source, they are not the same. You can register diagnostic areas using the logging component of the SPGuidance set, but this does not mean a corresponding event source is also created. In fact, event sources need to be registered on each front-end separately with sufficient permissions, before the logging component can write to the event log using the diagnostic area as the event source. So how would you create the event sources on each front-end? Well, there are a couple of possible approaches:

  1. Use PowerShell to create the sources on each front-end remotely
  2. Use a Timer Job to run custom code on each front-end that registers the event source.

In this post, I will show how to do that from PowerShell. These are only two lines of code and the script can be run from a remote location on each front-end.

# First load object models to use

# call the registration method to ensure all registered diagnostic areas are also registered as event sources

In this script, we first load the assembly Microsoft.Practices.SharePoint.Common.dll. We assume here that the assembly is available from the GAC. In my next post, the solution provided will ensure these assemblies are deployed to the GAC for use. Once we have done that, we can call the static EnsureConfiguredAreasRegistered method of the DiagnosticsAreaEventSource class that will iterate through all the configured and registered diagnostic areas and ensures that an event source is registered for that. The event sources will be registered on the Application event log. During the next couple of days, I will also investigate the possibility of registering the sources to different logs.

In the next post, I will show a custom solution on how to create additional diagnostic areas and use a timer job to ensure the event sources are created at the front end. Till next time!

Using PowerShell to deploy SharePoint Solutions (WSP)

The STSADM command line application worked well with previous versions of SharePoint. But the world is progressing and PowerShell will be the new administrative tool for SharePoint. In previous articles, I already showed some amazing powerful scripts that otherwise would require more lines of code. PowerShell offers some great advantages in large farms, as they can be run remotely on target machines, can be signed and therefore be controlled. Building up a repository of scripts or cmdlets to execute common tasks would be worthwhile in the long run.

First off an important thing to note here that this will only work with SharePoint 2010. There are no PowerShell snapins available for 2007, although you could create your own off course. And when run from a SharePoint 2010 Management Shell, the snapins are loaded automatically. But what if you just use the ‘normal’ console? Well, then you would have to register the snapin yourself. Fortunately, MS has already created the PowerShell script that is needed, located at:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\Config\PowerShell\Registration\SharePoint.ps1.

You could include this script in your scripts to be run first, or just include the command that registers the snapin:

Add-PSSnapin Microsoft.SharePoint.PowerShell

This article covers one of the most basic tasks one would do when administrating SharePoint: Deploy SharePoint solutions (WSP) and enable/disable features.

Working with Solutions

In the ‘old’ days (let us not forget that the stsadm is still there and we have a lot of SharePoint 2007 installations across the globe), the following stsadm command could be used to add a SharePoint solution to SharePoint:

stsadm –o addsolution –filename “D:\Deploy\MySharePointSolution.wsp

We used the following command to deploy the solution once installed to a specific web application:

stsadm –o deploysolution –name MySharePointSolution.wsp –url http://myspwebappp –allowgacdeployment –immediate

If we would upgrade an existing solution, we would use the following:

stsadm –o upgradesolution –name MySharePointSolution.wsp –filename “D:\Deploy\MySharePointSolution.wsp” -immediate

And finally, we used the following commands to retract and delete a specific solution from the web application:

stsadm –o retractsolution –name MySharePointSolution.wsp –url http://myspwebapp –immediate
stsadm –o deletesolution –name MySharePointSolution.wsp

Now, let us see how we could do above operations with PowerShell. For this, we use the following PowerShell commands:

Install-SPSolution –Identity MySharePointSolution.wsp –WebApplication http://myspwebapp –GACDeployment

If you would like to add the solution as sandboxed, you would use the Install-SPUserSolution command instead. To upgrade a solution, we specify which solution is to be updated and with which new solution file:

Update-SPSolution –Identity MySharePointSolution.wsp –LiteralPath “D:\Deploy\MySharePointSolution.wsp” –GacDeployment

To retract and remove a solution, we use the following commands:

Uninstall-SPSolution –Identity MySharePointSolution.wsp –WebApplication http://myspwebapp
Remove-SPSolution–Identity MySharePointSolution.wsp

Working with features

Similarly, commands exist for working with features. The stsadm equivalents:

stsadm –o activatefeature –name MyFeatureName –url http://myspwebapp
stsadm –o deactivatefeature –name MyFeatureName –url http://myspwebapp

Needless to say, there are easy equivalents in PowerShell:

Enable-SPFeature –Identity MyFeatureNameOrGuid –url http://myspwebapp
Disable-SPFeature –Identity MyFeatureNameOrGuid –url http://myspwebapp

As you can see, PowerShell will completely replace stsadm as the administrative command line tool for SharePoint. Better to start using it as the next version of SharePoint will not have a stsadm command line tool I suspect. To conclude, let us take a look at a script that enables a certain feature across all site collections and sites in a farm. As an example, I have taken the SharePoint Server Enterprise Site Features feature with ID 0806d127-06e6-447a-980e-2e90b03101b8.

Add-PSSnapin Microsoft.SharePoint.PowerShell
$WebApplications = Get-SPWebApplication

foreach ($webapp in $WebApplications) {
  $Id = $webapp.Id
  Write-Host “Processing web application $Id …”
  $sites = $webapp.Sites
  foreach ($site in $sites) {
    Write-Host Processing site $site.Id
    $webs = $site.AllWebs
    foreach ($web in $webs) {
      Write-Host Processing web $web.Title
      if ($web.Features[“0806d127-06e6-447a-980e-2e90b03101b8”] -eq $null) {
        Enable-SPFeature -Identity 0806d127-06e6-447a-980e-2e90b03101b8 -url $web.Url -Confirm:$false
      } else {
        Disable-SPFeature -Identity 0806d127-06e6-447a-980e-2e90b03101b8 -url $web.Url -Confirm:$false

Please note though that above script will work for small site collections. But for larger object hierarchies, you will need to include proper memory management (SPAssignment) to ensure proper release of memory.

As always, have fun coding.

Using Powershell to change registry keys for search crawler

In one of my earlier posts, I described a way to use PowerShell to change settings in a SharePoint 2007 farm.  That started out as my first PowerShell script and I have witnessed the power behind it all.

In our project, we needed a server wide adjustment of the registry for the SharePoint index servers across all farms. Of course, multiple ways to do this, but here is where PowerShell shows its power. I needed to change two registry settings, both covering the maximum file size that is crawled by the indexer. By default, this is 16 MB (mutiplied by 4), leaving a total of 64 MB indexed in each file. As we now enlarged trhe maximum upload size to 100 MB, we needed the crawl settings to be adjusted. To be honest, I was quite surprised it would only take me two lines of script to make this work. The registry keys in question were those below:


And to change these, the following lines of script would suffice. I have also added some additional lines to check whether we actually are at the index server, otherwise, these changes would have no effect. Pay special attention to the way the registry is accessed. In principle, it is accessed as a file path.

Set Search Crawler Settings

Write-Host “Set registry values for search”
Write-Host “=======================================================================”
Write-Host “”

if ( (Get-Itemproperty  -Path “hklm:\SOFTWARE\Microsoft\Office Server\12.0\Search\Global”).Index -eq 1 ) {
    Write-Host -f green “Validated that this server is the index Server ” 
} else  {
    throw “This server is the not the SharePoint index Server ” 

Write-Host “Processing MaxTextFilterBytes”
set-itemproperty “hklm:\system\currentcontrolset\control\contentindex” MaxTextFilterBytes -type “DWord” -value “104857600” -force

Write-Host -f green “Done…”
Write-Host “Processing MaxDownloadSize”
set-itemproperty “hklm:\software\microsoft\office server\12.0\search\global\gathering manager” MaxDownloadSize -type “DWord” -value “26214400” -force

Write-Host -f green “Done…”
Write-Host -f green “Script completed”
Write-Host “=======================================================================”
Write-Host “”

In addition to these registry changes, a couple of more settings need to be set to get the entire maximum upload size working. Above registry changes instruct the search crawler to enlarge the crawled file size. But this still does not allow SharePoint to upload larger files.  Besides SharePoint changes, OS level changes also need to be make on the client side to allow the WebDAV protocol to upload larger files. These are however out of scope of this blog post. In short, three steps are needed to support larger files on SharePoint:

1. Change the crawler settings to support larger files in the registry.
2. Change the Maximum File Size for the Web Application.
3. Change the connection time out setting on the SharePoint search service. (OSearch)

To change the crawler settings, the PowerShell script is located above. To execute steps 2 and 3 in above list, the following PowerShell scripts do the job:

Set Maximum File Size for Web Application

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
if ($farm -eq $null ) {
    throw “Could not connect to the SharePoint farm”

Write-Host “”
Write-Host “====================================================================”
Write-Host “”
$websvcs = new-object  Microsoft.SharePoint.Administration.SPWebServiceCollection($farm)
if ($websvcs.Length -eq 0 ) {
    throw “Could not connect to any SharePoint Web Service in the farm”
$FileSize = 100
$MaximumFileSize = 0

foreach ($websvc in $websvcs) {
    foreach ($webapp in $websvc.WebApplications) {
 if (($webapp.MaximumFileSize -ne $FileSize) -and ($webapp.MaximumFileSize -lt $FileSize))
  Write-Host “Set file size for web application $webapp.Name”
  $webapp.MaximumFileSize = $FileSize
  $MaximumFileSize = $webapp.MaximumFileSize
  Write-Host -f green “New file size $MaximumFileSize MB”
 } else {
         Write-Host -f green “Maximum file size for $($webapp.Name) was already set to or larger than $FileSize MB”
Write-Host -f green “Script completed”
Write-Host “====================================================================”

Set Connection TimeOut for Search Crawler

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
if ($farm -eq $null ) {
    throw “Could not connect to the SharePoint farm”

Write-Host “====================================================================”
Write-Host “”

$searchsvcs = @($farm.Services | where -FilterScript {$_.GetType() -eq [Microsoft.Office.Server.Search.Administration.SearchService]})
if ($searchsvcs.Length -eq 0 ) {
    throw “Could not connect to any SharePoint Search Service in the farm”

$TimeOut = 90
foreach ($searchsvc in $searchsvcs) {
    if (($searchsvc.ConnectionTimeOut -ne $Timeout) -or ($searchsvc.AcknowledgementTimeout -ne $Timeout))
        Write-Host “Set connection and acknoledgement timeouts for $($searchsvc.Name) to $Timeout”
        $searchsvc.ConnectionTimeOut = $Timeout;
        $searchsvc.AcknowledgementTimeout = $Timeout;
 Write-Host -f green “Done…”

    } else {
        Write-Host -f green “Connection timeout for $($searchsvc.Name) was already set to $Timeout”

Write-Host -f green “Script completed”
Write-Host “====================================================================”

Thats it! Using three simple scripts, we can change the settings in our entire farm to use new file upload settings and have it supported by the sarch crawler.


Using PowerShell 1.0 to change web application setting in SharePoint 2007

Sure, PowerShell is already available for a long time on Windows 2003, also in combination with SharePoint 2007. But untill this time, I could avoid the use 😉

But with PowerShell 2.0 becoming more important to SharePoint 2010, it was time to dive a little bit into this scripting language.
At my current customer, the maximum upload size for documents needed to be increased to 100 MB, from the default setting of 50 Mb. Obviously, we could do this using the Central Admin, but it becomes more of a problem when there are a lot of web applications, hence the choice for scripting. Also, a lot of other settings on different layers need to be adjusted to make this work, for example WebDAV settings in Vista and registry settings for the crawler, but this post only covers the PowerShell script to change the setting in the web application general settings.

So, below is my first PowerShell script. Note that this script is by no means the best one. It could be extended with exception handling, parameters to specify action and size, but for the purpose of this post, it is clear enough.

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local

Write-Host("Get all web applications within each web service")
$websvcs = @($farm.Services | where -FilterScript {$_.GetType() -eq [Microsoft.SharePoint.Administration.SPWebService]})

foreach ($websvc in $websvcs) {
  foreach ($webpp in $websvc.WebApplications) {
    $webapp.MaximumFileSize = 100

Not much exiting stuff going on here right? First I load the Microsoft.SharePoint.dll assembly by calling the LoadWithPartialName method of the System.Reflection.Assembly class. Because this method is static, we use the ‘::’ operator. Once loaded, we get the local farm by calling the SPFarm.Local method. Again, becuase Local is a static method, we use the ‘::’ operator.

When done, we get all SPWebService objects within the Services collection of the Farm. This line is a little less obvious. In C#, we would use the SPFarm.Services.GetValue<SPWebService>() method. In PowerShell, we filter the Services collection by using a sort of SQL like syntax. Get all services where type (GetType()) equals (-eq) Microsoft.SharePoint.Administration.SPWebService. The rest speaks for itself and looks quite a lot like C# code.

There you have it, my first PowerShell 😉 Naturally, we could create a simple command line utility that does the same using C#, but these scripts are created faster and are also easy adjustable to fit needs.

So, in short, with SharePoint 2010 embracing PowerShell, we have no choice then to venture in the world of PowerShell.

Till next time!