How to warm-up SharePoint or other web applications and WCF (SOAP) services with PowerShell

There are many reasons you might want to warm-up a web application occasionally. It can be after a fresh deployment or on a regular basis after recycling application pools. Some times you might also need to warm-up SOAP services without going through front-end.

It might seems to be any easy task specially if you have PowerShell 3.0 or higher on your servers, but after Googling a while and reviewing some of the top hits I discovered that each solution is missing a part. Some only work in a single server scenario and some has forgotten that each HTTP response might contain links to scripts and images that we need to download and finally I could not find anything for SOAP services that just works. Long story short I decided to put together a simple script that just works and is easy to change to everyone’s needs.

Please note that my only assumption is you have PowerShell 3.0+ in your servers.

Currently the script takes care of the following tasks, but I will most likely improve it to cover other useful scenarios.

  • Calling SOAP operations and sending parameters and custom headers
  • Calling front-end URIs and downloading scripts and images that are local to the front-end
  • Logging to a configurable folder and file name
  • Cleaning up old log files

Currently, I have the following points in mind to improve the script.

  • Put configuration in a different file.
  • Improve function definitions (named and typed parameters and description).
  • Default values for parameters when it makes sense (e.g. log folder can be the current folder).
  • Support REST services.

I’m open to any suggestion and feature request. Please let me know if you found it useful or if have got something wrong.

How to warm-up SharePoint or other web applications and WCF (SOAP) services with PowerShell

How to create search query content source in SharePoint using PowerShell

They are called Content Sources in the graphical user interface of SharePoint and Search Query Content Source when using PowerShell. A content source is basically pointing to a source of data that can be indexed in the search database. Because the data is indexed, when later users run queries the result is returned almost instantaneous. It is very easy to add a content source by using SharePoint Central Administration, but you might need to create a long list of content sources in a batch for example as part of a disaster recovery process or many other reasons. Here is one way I do it in a PowerShell script.

$contentSourceConfig = @(
    @{
        Name = "Articles"
        StartAddresses = "http://mydomain1/site1/fr,http://mydomain1/site1/nl,http://mydomain1/site1/en"
    },
    @{
        Name = "Technical"
        StartAddresses = "http://mydomain1/site2/fr,http://mydomain1/site2/nl,http://mydomain1/site2/en"
    }
)

foreach($config in $contentSourceConfig) {
    $contentSourceName = $config.Name
    $startAddresses = $config.StartAddresses
    $contentSource = Get-SPEnterpriseSearchCrawlContentSource $contentSourceName -SearchApplication $ssa -ErrorAction SilentlyContinue
    if ($contentSource) { $contentSource.Delete() }
    $contentSource = New-SPEnterpriseSearchCrawlContentSource $contentSourceName -Type "Web" -StartAddresses $startAddresses -SearchApplication $ssa
    Write-Host "Search crawl content source: $contentSourceName created successfully."
}

As you see in the above example I have put all the required configuration in one array of custom objects. If you need to add more content sources you may simply copy-past one and change the properties. This way the configuration is separated and easier to read or change while still it is in the same file with the script so you won’t have to rely on extra XML file(s) to put beside the script.

If you are more comfortable by separating the configuration from the script. You can cut the first part and past it to another script file or use the XML approach.

For more details about the cmdlets I’ve used I suggest you have a look on the following MSDN articles:

How to create search query content source in SharePoint using PowerShell

First step in developing apps for SharePoint Online – Enabling F5

It’s Just a quick post to share one of my first experiences with SharePoint online and that’s how to enable F5 experience in Visual Studio. When you start writing your first App for SharePoint Online you might get the same error as me, saying that “Sideloading of apps is not enabled on this site”

Sideloading of apps is not enabled on this site
Sideloading of apps is not enabled on this site

It’s because the “Developer” feature is not activated by default and you need to activate it manually, but since it’s an online version of SharePoint things are a little bit different that you local development environment (a good article on how to prepare your local development environment) and you need to use CSOM (Client Side Object Model). I have just translated the c# equivalent to a few lines of PowerShell code so you can type it into your SharePoint Online Management Shell (if you have not installed it, you can download it from here). Here is the code:

<br />$siteurl = "https://yourwebsite.sharepoint.com"<br />$username = "yourusername"<br />$password = ConvertTo-SecureString -String 'yourpassword!' -AsPlainText -Force<br />[Microsoft.SharePoint.Client.ClientContext] $context = New-Object Microsoft.SharePoint.Client.ClientContext($siteurl)<br />[Microsoft.SharePoint.Client.SharePointOnlineCredentials] $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)<br />$context.Credentials = $credentials<br />$site = $cc.Site<br />$sideLoadingGuid = New-Object System.Guid "AE3A1339-61F5-4f8f-81A7-ABD2DA956A7D"<br />$site.Features.Add($sideLoadingGuid, $true, [Microsoft.SharePoint.Client.FeatureDefinitionScope]::None)<br />$context.ExecuteQuery();<br />
First step in developing apps for SharePoint Online – Enabling F5

Add / Remove event receivers to list / content types in SharePoint with PowerShell

Although it’s simple but it’s a little bit tricky. Adding / removing an event receiver to a list and content type is the same you just need to use the appropriate collection is an SPWeb object.

Here is how to add / remove an event receiver to / from a list:

# The following code registers an event receiver for when an item is being added to a list
$web = Get-SPWeb "http://yourwebsiteurl"
$list = $web.Lists["your list name"]
$list.EventReceivers.Add("ItemAdding", "Full Assembly Name", "Full.Class.Name")

Removing an event receiver is as easy as:

# Be careful about the index value for when you have more than one event receiver!
$list.EventReceiver[0].Delete()

As you can see below adding an event receiver to a content type is very similar:

# The following code registers an event receiver for when an item is being added to a list
$web = Get-SPWeb "http://yourwebsiteurl"
$ctype = $web.ContentTypes["your content type name"]
$ctype.EventReceivers.Add("ItemAdding", "Full Assembly Name", "Full.Class.Name")

And so is deleting it:

# Be careful about the index value for when you have more than one event receiver!
$ctype.EventReceiver[0].Delete()

Now more important is the tricky part. If you have used this content type to create other / list instances then you should also call the following command to propagate the change:

$ctype.Update($true)
Add / Remove event receivers to list / content types in SharePoint with PowerShell

How to recreate web application in SharePoint by Powershell

Some times you might need to recreate a web application (probably on you development box) to do a complete deployment and don’t want to go through all the those options in Central Administration. here is the PowerShell code. Just put your specific values save it into a .ps1 file and run it whenever you want:

# First the SharePoint Snapin
$snapin = Get-PSSnapin | ? { $_.Name -like "Microsoft.SharePoint.PowerShell"; }
if ($snapin -eq $null)
{
Add-PSSnapin "Microsoft.SharePoint.PowerShell"         `
-Verbose:$false                         `
-ErrorAction SilentlyContinue             `
-ErrorVariable err;

if (![string]::IsNullOrEmpty($err))
{ Write-Host $err; $result = $false; }
else
{  Write-Host "SnapIn successfully added";  $result = $true;  }
}
else
{  Write-Host "SnapIn already added"; $result = $true; }

# This function first deletes the web app if it exists
# Then tries to create it again
function RecreateWebApp([string]$webAppUrl,
[string]$webAppName,
[string]$appPoolAccount,
[string]$dbName,
[string]$hostHeader,
[int]$port)
{
$exists = (Get-SPWeb $webAppUrl -ErrorAction SilentlyContinue) -ne $null;

if ($exists)
{
Remove-SPWebApplication -Identity $webAppUrl -DeleteIISSite -RemoveContentDatabases;
}
New-SPWebApplication -Name $webAppName -ApplicationPool $webAppName -ApplicationPoolAccount $appPoolAccount -DatabaseName $dbName -HostHeader $hostHeader -Port 80;
}

# Change the following to include your specific settings:
RecreateWebApp "http://www.contoso.com" "Contoso" "Admin" "Contoso_Content" "www.contoso.com" 80;
How to recreate web application in SharePoint by Powershell

How to view / change web site properties in SharePoint by PowerShell

In SharePoint, Property bags are usually used to store values / configurations related to a web site. Reading / Writing them via PowerShell is really easy just fire up “SharePoint 2010 Management Shell” from the Start Menu and type the following commands:

$web = Get-SPWeb "http://yourwebsite"
$web.Properties["PropertyName"] = "Property Value"
$web.Properties.Update()
How to view / change web site properties in SharePoint by PowerShell

How to change OSearch14 account (user)?

How to change search service account using SharePoint Central Administration

The simplest way to change the account of a service in SharePoint is to:

  1. Run Central Administrator
  2. Go to Security > Configure service accounts
  3. Select “Windows Service – SharePoint Server Search”
  4. In “Select an account for this component” select the account that you want and if it is not in the list, click “Register new managed account” and add it easily.

How to change search service account using PowerShell

But sometimes it’s not as easy as above to change a service account in SharePoint. For example you have installed SharePoint on a server for development whiout adding “Active Directory Domain Services” server role. In that case you can only add Managed Accounts through PowerShell and even though it won’t be displayed on managed account list in Central Administration and you can only use PowerShell to assign them to different services.

Step1 – Here is how to add a managed account in PowerShell:

First, go to the Start menu, then “Microsoft SharePoint 2010 Products” and run SharePoint 2010 Management Shell” which will run PowerShell and adds SharePoint Snapin so you can run SharePoit’s cmdlets. Now you can type the following commands:

$cred = Get-Credential  "Username"
New-SPManagedAccount -Credential $cred

Step 2 – How to assign it to OSearch14 (Enterprise Search):

$account = Get-SPManagedAccount -Identity "Username"
$procId = (Get-SPEnterpriseSearchService).get_ProcessIdentity()
$procId.CurrentIdentityType = "SpecificUser"
$procId.ManagedAccount = $account
$procId.Update()
$procId.Deploy()

Remember that the last line is important beacuse you won’t see any changes until this step. It actually restarts the service with the recently assigned account.

How to change OSearch14 account (user)?