itramblings

Ramblings from an IT manager and long time developer.

By

Office 365 – Single Sign-On for SharePoint, Skydrive, CRM, etc. via Smart Links

Office 365 – Single Sign-On for SharePoint, Skydrive, CRM, etc. via Smart Links

 

Synopsis: One of the biggest problems I have seen
with Office 365 is ease in accessibility to all of the Office365
resources.  As pointed out on many of the Microsoft forums, SharePoint,
CRM, Skydrive, etc. do not automatically complete a single-sign on
request when browsing the website.

Problem: When a user
browses https://mydomain.sharepoint.com for example, the user is
prompted to enter in their email address.  What a user expects is that
they should automatically be logged in and see sharepoint when
navigating to https://mydomain.sharepoint.com  Additionally, for
whatever reason, users cannot remember the website address to
https://mydomain.sharepoint.com  Instead, they want to do something like
http://sharepoint.mydomain.com

Solution: Create name branded “fancy URLs” that will complete an idp claim to give the user a true SSO experience.

  • http://owa.mydomain.com
  • http://sharepoint.mydomain.com
  • http://skydrive.mydomain.com
  • http://crm.mydomain.com

Solution:

  1. Open up Internet Explorer
  2. Navigate to https://mydomain.sharepoint.com
    Sign into Office 365
  3. Press F12 to open up the developer tools console (I am running IE
    11, the console looks way different than previous versions of IE)
    Sign into Office 365 - Developer Console
  4. Scroll down and select the icon that looks like a little WiFi antenna
    Sign into Office 365 - Developer Console - Network
  5. Click the green play button
    Sign into Office 365 - Developer Console - Network - Start Capture
  6. Type in your email address as you would to login to sharepoint (myusername@mydomain.com)
  7. You should be redirected to your ADFS server and inside the network
    console, you should see a link like
    https://sts.mydomain.com/adfs/ls/?………………  Copy this link into notepad.
    Office 365 - Federated URL
  8. Remove the extra stuff from the debug console
    Before
    Office 365 - Federated URL - Notepad

    After
    Office 365 - Federated URL - Cleaned - Notepad
  9. Remove everything from cbcxt=….. to wa=wsignin1.0
    Office 365 - Federated URL - cbcxt removed
  10. Remove the ct%3D1386214464%26 and bk%3D1386214464%26 parameters
    Office 365 - Federated URL - ct and bk removed
  11. Next, open up another new notepad document named index.html and paste the following text into it
    1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>
      <title>CRM</title>
      <meta http-equiv=”refresh” content=”0; url=https://sts.mydomain.com link goes here” /></head>

      <body>

      </body>
      </html>
      Redirect to URL template

  12. Replace https://sts.mydomain.com link goes here with your new smart link and save the document.
    Redirect to federated URL
  13. Upload the index.html file to one of your your webservers
  14. Create a new A record called sharepoint.mydomain.com pointing to your webserver
  15. Now when a user browses http://sharepoint.mydomain.com, the user
    will automatically be redirected to your secure ADFS Proxy and
    authenticate automatically.

You will need to repeat the steps above for each of the Office 365
products your company uses.  The federated addresses do change, so you
will have to follow all of the steps over again for each Smart Link you
wish to create.

NOTES:
Here is an official article on creating smart links: http://community.office365.com/en-us/wikis/sso/using-smart-links-or-idp-initiated-authentication-with-office-365.aspx

By

ULS Logs and the ULSViewer

u might have stumbled across this blog entry when looking for information on the ULS. If that is the case, while I will not
go into great detail on the ULS I can at least tell you that it stands for stands for Unified Logging Service and is a corner
stone of SharePoint troubleshooting and it is the first place I recommend looking at to start tracking down the details of any
errors you might be encountering. If you are looking for a decent article on the ULS I’d recommend checking out the general
MSDN article that gives a general
overview.

Now, assuming that you have at least a basic understanding of the ULS and where the files can be found (default is the
“SharePoint HIVE”Logs folder). If you open one of the files up, I am willing to bet that you would find yourself wondering
how on earth you can make heads or tails of the information stored in the file and if you have a large farm, how you can pull
it all together so you can track down any issues quickly and more efficiently. Well you are in luck as one of the better tools
out there is free, full of features, and rather easy to use. This tool is called the ULSViewer and can be downloaded from
here or
here.

ULSViewer can be used in different modes. The log can be read from log files, real time ULS log, from multiple servers, or
even from the clipboard. Here’s some examples:

On a machine running SharePoint 2010, run ULS Viewer. Click File, Open From, then choose ULS (This could also be done by
simply press Ctrl+U).


clip_image001

Immediately the logs will be shown in real-time. From here you can do things like filter by message level by click the icons
in the of the tool bar


clip_image002

You can ask set filters based on what you are looking for (error message, correlation id, etc). You can do this by clicking
on the “filter” icon in the tool bar and then defining 1 or more filters.


clip_image003


clip_image004

Note: One of the great things you can also do is save filters and reuse them. I find that I have a number of filters that I
use over and over and this helps save a lot of time!

Another feature that I find really handy is the “Toggle Correlation Tree” button.


clip_image005


clip_image006
When you click on this it opens up a side panel that can show you a list of all of the correlation ids and when you click
on one of those nodes you immediately see the main area filters to show only the log entries related to that single correlation
id.

The reason why this is so useful is because in SharePoint we use correlation ids to trace a series of events that occurred
at once (like a transaction).

For example if you look at the screenshot below you’ll see that I selected the correlation id
‘ce44ed9c-e3b3-c0ad-3409-5e8c8d8d317f’ and this one appears to be related to a UserProfileImport Sync job.


clip_image007

If you’re running this on a development machine or are trying to track down an error that doesn’t happen regularly
another good feature is the notifications. You can enable notification by level in side of ULS Viewer (by default it will pop
up notification for Critical message). For example in this screenshot, when Health Analyzer checked my machine for a security
rule, it wrote a critical message into the log. With ULS Viewer, you can quickly identify the location of the message. If
there’s an exception, you can also check the detail of that.


clip_image008

Another great feature is the ability to open up multiple ULS logs from different servers. So if you have a 4 or 5 server
farm, you could either review each log individually or you could open them up as a “FARM” and let ULSView take over the
complicated work of combining the log files into a single view. You can do this either from the tool bar by clicking on the
“farm” icon or by going to File -> Open From -> Farm (Ctrl+ R)

Farm Icon


clip_image009

File -> Open From


clip_image010

Which then opens this dialog


clip_image011

From here you can add all of your servers (NetBios, FQDN, or IP addresses work just fine) and then specify a share that is
available on ALL of the servers list.

Tip: The SAME share must be available on all servers for this to work. I normally create a standard share on all of my
SharePoint servers called “UlsLogs” and grant read only access to the development and operations teams.

Also another useful feature is that once you have configure ULSView for your environment (include what servers/files are
being monitored), you can save everything to a “workspace”. This workspace can be shared with others and opened at any
time. This provides a very quick way to start viewing a farm.


clip_image012

Tip: I usually create one workspace per environment and share what with the development and operations team.

By

Project 2013 and Project Server 2013 Technical Training Links

Microsoft Training Links

Project 2013 training for IT pros and developers

General Link: http://technet.microsoft.com/en-us/office/dn756399

Development Links

Administration Links:

By

Office Web Apps 2013 Server Install and Configuration

Copied from here

Installing Office Web Apps

Office Web Apps 2013 is a stand-alone server web application that provides capabilities to open and render a Microsoft Office Word, Excel, PowerPoint, or OneNote document as a web page. Microsoft SharePoint 2013, Exchange 2013, and Lync 2013 can share the rendering service to display Office documents in those applications as a web page. Additionally, when accessed from within a SharePoint 2013 farm, Office Web Apps also enables rich editing features for those documents.

Note: You cannot install Office Web Apps on the same server as SharePoint 2013

Please follow the server preparation process in the following sections for the appropriate server, either Windows Server 2008 R2 or Windows Server 2012.

Windows Server 2008 R2 Preparation

Start by installing the following prerequisite software for Windows Server 2008 R2:

Open a PowerShell command running as an Administrator and execute the following commands to install the required roles and services for Office Web Apps.

Import-Module ServerManager
## Run the following command as a single line
Add-WindowsFeature Web-Server,Web-WebServer,Web-Common-Http,Web-Static-Content,Web-App-Dev,Web-Asp-Net,Web-Net-Ext,Web-ISAPI-Ext,Web-ISAPI-Filter,Web-Includes,Web-Security,Web-Windows-Auth,Web-Filtering,Web-Stat-Compression,Web-Dyn-Compression,Web-Mgmt-Console,Ink-Handwriting,IH-Ink-Support

Please continue with the “Office Web Apps Installation” section below.

Windows Server 2012 Preparation

To begin, open a PowerShell command running as an Administrator and execute the following commands to install the required roles and services for Office Web Apps.

Add-WindowsFeature Web-Server,Web-Mgmt-Tools,Web-Mgmt-Console,Web-WebServer,Web-Common-Http,Web-Default-Doc,Web-Static-Content,Web-Performance,Web-Stat-Compression,Web-Dyn-Compression,Web-Security,Web-Filtering,Web-Windows-Auth,Web-App-Dev,Web-Net-Ext45,Web-Asp-Net45,Web-ISAPI-Ext,Web-ISAPI-Filter,Web-Includes,InkandHandwritingServices

Please continue with the “Office Web Apps Installation” section below.

Office Web Apps Installation

Open and run the Office Web Apps setup.exe media to launch the setup wizard.

  1. In the Office Web Apps Server 2013 Wizard, on the Read the Microsoft Software License Terms page, select I accept the terms of this agreement and then select Continue.
  2. On the Choose a file location page, select the folder where you want the Office Web Apps Server files to be installed (for example, C:Program FilesMicrosoft Office Web Apps), and then select Install Now. Note that, if this folder does not exist, Setup will create it for you.
    The Choose a file location screen on the Office Web Apps install wizard.

    The Choose a file location screen on the Office Web Apps install wizard.

  3. When Setup finishes installing Office Web Apps Server, choose Close.

After installing the Office Web Apps 2013 server software, you are ready to install any additional add-ins and updates. You can also install any language packs your farm requires. To install the language packs, run the setup media for each of the language packs you desire.

If applicable, install the latest service pack Microsoft has released for Office Web Apps 2013 and then apply the latest service packs Microsoft has released for Office Web Apps 2013 language packs.

Finally, check for updates on Microsoft Update in the server’s control panel.

Configuring Office Web Apps

This section describes how to configure an Office Web Apps farm and join servers to it.

Important: Low memory conditions can cause Office document previews to fail in Office Web Apps. Verify that any servers that run Office Web Apps have sufficient memory.

On the first server for the Office Web Apps farm, execute the following PowerShell command to provision the farm:

New-OfficeWebAppsFarm -InternalUrl "https://office1.contoso.com" -ExternalUrl "https://office.contoso.com" -SSLOffloaded –EditingEnabled

The SSLOffloaded command switch configures Office Web Apps for hardware load-balancing, where the load-balancing device manages the SSL certificate and then relays the request to an Office Web Apps server over HTTP unencrypted traffic. This improves the overall performance but does require a secure network between the load-balancer and the Office Web Apps servers.

The following image provides an example of the expected output from the PowerShell command.

PowerShell results from configuring an Office Web Apps farm

PowerShell results from configuring an Office Web Apps farm

Critical: Before you can use the Office Web Apps farm, you must add your domain to the list of allowed hosts.

Run the following PowerShell command to add your domain to the list of allowed hosts, substituting your domain for “contoso.com.”

New-OfficeWebAppsHost -Domain contoso.com

Once you have provisioned an Office Web Apps farm and allowed your domain, you can join additional Office Web Apps servers to the farm. To join additional servers, install the Office Web Apps software by following the steps in the previous section and then execute the following PowerShell command.

New-OfficeWebAppsMachine –MachineToJoin “office1.contoso.com

You can test the Office Web Apps configuration by navigating to this URL and verifying it displays a Web app Open Platform Interface (WOPI)-discovery XML file: https://office.contoso.com/hosting/discovery

Note: For more information on deploying and configuring Office Web Apps, please see this TechNet article: http://technet.microsoft.com/jj219455

Configuring the Windows Firewall for Office Web Apps Traffic

On each Office Web Apps 2013 Server, you will need to set a firewall rule to allow Office Web Apps inter-farm traffic and HTTP/HTTPS traffic. Alternatively, you can disable the Windows Firewall if you choose and if you have another firewall solution.

You can set the Windows Firewall rules by navigating to the Control Panel, then click System and Security, then click Windows Firewall, and finally click Advanced settings. In the Inbound Rules area, ensure that the server allows connections on port 80 (HTTP) and port 443 (HTTPS). Add the port for the Office Web Apps inter-farm communication by following these steps:

  1. In the Windows Firewall with Advanced Security window, click Inbound Rules.
  2. In the Actions panel, click New rule…
  3. In the New Inbound Rule Wizard window, select Ports as the Rule Type and click Next.
  4. Select TCP and enter “809” for the Specific local ports. Click Next.
    Windows Firewall Port Rule for Office Web Apps communication

    Windows Firewall Port Rule for Office Web Apps communication

  5. Click Next. On the Profile screen, uncheck Public and click Next.
  6. On the Name screen, enter “Office Web Apps Inter-Farm Communication” and click Finish.

Configuring a SharePoint 2013 Farm for Office Web Apps

Logon to the SharePoint application server that hosts Central Administration and open the SharePoint 2013 Management Shell (PowerShell), running it as an administrator. Next, enter the following PowerShell command:

New-SPWOPIBinding -ServerName “office1.contoso.com

Run the following PowerShell command to enabled OAuth over HTTP.

$config = (get-spsecuritytokenserviceconfig)
$config.allowoauthoverhttp = $true
$config.update()

Run the following PowerShell command to change the WOPI zone to external-https.

Set-SPWOPIZone –zone “external-https”

Finally, verify that Office Web Apps is working by navigating to a SharePoint 2013 document library and verify that you can open a document as a web page.

Note: For more information on how to configure a SharePoint 2013 farm to use Office Web Apps and for troubleshooting information, please see this TechNet article: http://technet.microsoft.com/ff431687

 

By

System.ServiceModel.ServiceActivationException: The service ‘/SecurityTokenServiceApplication/securitytoken.svc’ cannot be activated due to an exception during compilation.

Re-post from here

Problem
I had performed an in-place upgrade of a Team Foundation Server from Windows Server 2012 to Windows Server 2012 R2. Overall, no issues detected until a couple of weeks later when all the Developers came back to work (after XMas break) and informed me that Documents were not available via the Visual Studio 2012 application. The following error was occurring in Visual Studio; Please contact your administrator. There was an error contacting the server.Technical information (for administrator): HTTP code 200: OK
So off to the TFS Server it was….

Research
First stop was the Event Viewer and there were two errors that I believe were related and occurring.

Error 1 – Event ID 3 System.ServiceModel 4.0.0.0 WebHost failed to process a request. 

Sender Information:System.ServiceModel.ServiceHostingEnvironment+HostingManager/4032828
Exception: System.ServiceModel.ServiceActivationException: The service ‘/SecurityTokenServiceApplication/securitytoken.svc’ cannot be activated
due to an exception during compilation. 

The exception message is: Exception has been thrown by the target of an invocation.. —> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> System.ArgumentNullException: Value cannot be null. Parameter name: certificate at System.IdentityModel.Tokens.X509SecurityToken..ctor(X509Certificate2 certificate, String id, Boolean clone, Boolean disposable) at System.IdentityModel.Tokens.X509SecurityToken..ctor(X509Certificate2 certificate) at Microsoft.SharePoint.Administration.Claims.SPSecurityTokenServiceManager.ConfigureTokenHandlerCollection(SPSecurityTokenServiceManager manager, SecurityTokenHandlerCollectionManager collectionManager, String key, SecurityTokenHandlerCollection& tokenHandlerCollection) at Microsoft.SharePoint.IdentityModel.SPSecurityTokenServiceConfiguration.ConfigureTokenHandlerCollectionForLocalIssuer(SPSecurityTokenServiceManager manager, SecurityTokenHandlerCollectionManager collectionManager, String key) at Microsoft.SharePoint.IdentityModel.SPSecurityTokenServiceConfiguration..ctor() — End of inner exception stack trace — at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean&bNeedSecurityCheck) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceHostFactory.CreateSecurityTokenServiceConfiguration(String constructorString) at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) at Microsoft.SharePoint.IdentityModel.SPSecurityTokenServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) — End of inner exception stack trace — at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String relativeVirtualPath, EventTraceActivity eventTraceActivity) Process Name: w3wp Process ID: 5664

Error 2 – Error ID 8306 SharePoint Foundation

An exception occurred when trying to issue security token:
The requested service, ‘http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc’ could not be activated.
See the server’s diagnostic trace logs for more information.. 

Error 3 – Error ID 6398

The Execute method of job definition Microsoft.Office.Server.UserProfiles.LMTRepopulationJob (ID 1b0c4725-fbcf-476d-af60-3aeabbdbd35c) threw an
exception. More information is included below. System.ServiceModel.ServiceActivationException 

The common problem here appeared to me to be with relation to the SecurityTokenServiceApplication, which can be sussed out within IIS… First I check that the Application Pool was configured with correct TFS Account and started…check Next went to browse the SecurityTokenServiceApplication web page itself (IIS Manager –> Sites –> SharePoint WebServices –> SecurityTokenServiceApplication, click on ‘Content View’ down at the bottom, right click on Securitytoken.svc and click Browse)…ERROR Basically you get a ‘Server Error in ‘/..’ Application + Error 1 above, or Internet Explorer cannot display the webpage etc.
From here I knew that the only way to fix this was to focus on the SecurityTokenServiceApplication web service but I wasn’t really sure where to start except that I knew this would be easy with PowerShell. 🙂

Thanks to gurus such as Syed and Abhishek Saigal, this is what fixed my issue.

Resolution
The below PowerShell commands re-provisions all the SharePoint Web Services.
Don’t worry about losing any data/applications on SharePoint, all will remain intact.
Run the following commands one by one on SharePoint PowerShell:

$h = Get-SPServiceHostconfig
$h.Provision()
$services = Get-SPServiceApplication
foreach ($service in $services) { $service.provision(); write-host $service.name} 

The output will take a little time and display each service one after another, patiently wait until it finishes.
Perform an IIS Reset and give another shot to browsing ‘http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc’ This page then displayed correctly, e.g. no error messages and Documents then worked within Visual Studio.

By

How to Profile a SharePoint/Project Server 2013 Workflow using dotTrace

Thought I’d put together a small “How to” for Profiling a SharePoint (or Project Server) 2013 workflow   The steps below are using a 10 day trial of dotTrace from jetbrains – that said, the same “idea” can be used by any profiling tool.

  1. First thing to do is download a copy of dotTrace from Jetbrains from their website (http://www.jetbrains.com/profiler/).  After you install this, you’ll have 10 days to use it without any limitations.
  2. Once it is installed, look for the dotTrace icon  , and start the application up.
  3. One the app is up and running, click on the “Attach to Process” button at the top
  4. Next, Find the process “Microsoft.Workflow.ServiceHost.exe”
  5. At this point you’re “tracing” in enabled.  And you will see a dialog like this
  6. Now you can run your tests that execute the workflow.  One you are done, click the “Get Snapshot” button on the tracing dialog
  7. At which point a snapshot file will open that contains all of the information (summary screen blow)
  8. Click on the “Plain List” icon
  9. At this point you can look through the various calls, the time each call took, etc (sample below)

     

By

New-SPConfigurationDatabase – This SharePoint farm currently has pending upgrades

New-SPConfigurationDatabase : The pipeline has been stopped.

At C:Usersadministrator.GENDesktopAutoSPInstallerSP2010AutoSPInstallerAutoSPInstaller.ps1:576 char:31

+             New-SPConfigurationDatabase <<<<  –DatabaseName “$ConfigDB” –DatabaseServer “$DBServer” –AdministrationContentDatabaseName “$CentralAdminContentDB” –Passphrase $SecPhrase –FarmCredentials $Cred_Farm

    + CategoryInfo          : InvalidData: (Microsoft.Share…urationDatabase:SPCmdletNewSPConfigurationDatabase) [New-SPConfigurationDatabase], PipelineStoppedException

    + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletNewSPConfigurationDatabase

Microsoft.SharePoint.SPException: This SharePoint farm currently has pending upgrades.  The cmdlet New-SPConfigurationDatabase cannot be executed until the upgrade is completed.

   at System.Management.Automation.MshCommandRuntime.ThrowTerminatingError(ErrorRecord errorRecord)

This SharePoint farm currently has pending upgrades.  The cmdlet New-SPConfigurationDatabase cannot be executed until the upgrade is completed.

At C:Usersadministrator.GENDesktopAutoSPInstallerSP2010AutoSPInstallerAutoSPInstaller.ps1:576 char:31

+                                             New-SPConfigurationDatabase <<<<  –DatabaseName “$ConfigDB” –DatabaseServer “$DBServer” –AdministrationContentDatabaseName “$CentralAdminContentDB” –Passphrase $SecPhrase –FarmCredentials $Cred_Farm

    + CategoryInfo          : InvalidOperation: (:) [New-SPConfigurationDatabase], SPException

    + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletNewSPConfigurationDatabase

 

luckily there is a pretty easy fix — run the following command and it will fix the issue (note: you can ignore the error that the command returns)

 

psconfig -cmd upgrade -inplace b2b -wait -force

 

By

What is SkyDrive Pro in SharePoint 2013

Great article can be fond here: http://en.share-gate.com/blog/what-is-skydrive-pro-in-sharepoint-2013

By

Export SharePoint Terms Group to XML

Here is a PowerShell script to export SharePoint Term Groups to XML

 

param(
	[string]$siteUrl = "http://sharepoint.local:2013",
	[string]$termGroup = "Sample Term Group",
	[string]$exportPath = $null
)


function Add-Snapin {
	if ((Get-PSSnapin -Name Microsoft.Sharepoint.Powershell -ErrorAction SilentlyContinue) -eq $null) {
		$global:SPSnapinAdded = $true
		Write-Host "Adding SharePoint module to PowerShell" -NoNewline
		Add-PSSnapin Microsoft.Sharepoint.Powershell -ErrorAction Stop
		Write-Host " - Done."
	}

	Write-Host "Adding Microsoft.SharePoint assembly" -NoNewline
	Add-Type -AssemblyName "Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
	# Disable the above line and enable the line below for SharePoint 2013
	# Add-Type -AssemblyName "Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
	Write-Host " - Done."
}

function Remove-Snapin {
	if ($global:SPSnapinAdded -eq $true) {
		Write-Host "Removing SharePoint module from PowerShell" -NoNewline
		Remove-PSSnapin Microsoft.Sharepoint.Powershell -ErrorAction SilentlyContinue
		Write-Host " - Done."
	}
}

function Get-ScriptDirectory
{
	$Invocation = (Get-Variable MyInvocation -Scope 1).Value
	return Split-Path $Invocation.MyCommand.Path
}

function Export-SPTerms {
    param (
        [string]$siteUrl = $(Read-Host -prompt "Please provide the site collection URL"),
        [string]$termGroupName = $(Read-Host -prompt "Please provide the term group name to export"),
        [string]$saveLocation = $(Read-Host -prompt "Please provide the path of the folder to save the CSV file to")
    )

	if ([IO.Directory]::Exists($saveLocation) -eq $false)
	{
		New-Item ($saveLocation) -Type Directory | Out-Null
	}

	Write-Host "Getting Taxonomy Session";
	$taxonomySession = Get-SPTaxonomySession -site $siteUrl
	$taxonomyTermStore =  $taxonomySession.TermStores | Select Name
	$termStore = $taxonomySession.TermStores[$taxonomyTermStore.Name]
	$fileRootNoteCreated = $false;

	# Ampersands are stored as full width ampersands (see http://www.fileformat.info/info/unicode/char/ff06/index.htm)
	[Byte[]] $amp = 0xEF,0xBC,0x86

	Write-Host "Looping through Term store Groups to find: '$termGroupName'"
	foreach ($group in $termStore.Groups) {
		Write-Host "Checking: '$($group.Name)'"
		$groupName = $group.Name.Replace([System.Text.Encoding]::UTF8.GetString($amp), "&");
		if ($groupName -eq $termGroupName) {

			Write-Host "Looping through Term sets"
		    foreach ($termSet in $group.TermSets) {
            	# Remove unsafe file system characters from file name
				$parsedFilename =  [regex]::replace($termSet.Name, "[^a-zA-Z0-9\-]", "_")

				$file = New-Object System.IO.StreamWriter($saveLocation + "termset_" + $parsedFilename + ".xml")

		        # Write out the headers
		        #$file.Writeline("Term Set Name,Term Set Description,LCID,Available for Tagging,Term Description,Level 1 Term, Level 2 Term,Level 3 Term,Level 4 Term,Level 5 Term,Level 6 Term,Level 7 Term")
				$file.Writeline("<termStore Name='" + $termStore.Name + "' GUID='" + $termStore.ID + "' Group='" + $groupName + "'>");
		        $file.Writeline("`t<termSet Name='" + $termSet.Name + "' GUID='" + $termSet.ID + "' Description='" + $termSet.Description + "'>");
				try {
					Export-SPTermSet $termSet.Terms
				}
				finally {
					$file.Writeline("`t</termSet>");
					$file.Writeline("</termStore>");
			        $file.Flush()
			        $file.Close()
				}
			}
		}
	}
}

function Export-SPTermSet {
    param (
        [Microsoft.SharePoint.Taxonomy.TermCollection]$terms,
		[int]$level = 1,
		[string]$previousTerms = ""
    )

	$tabCount = $level+1;
	if ($level -gt 1) {$tabCount = $tabCount + ($level-1);}

	if ($terms.Count -gt 0)
	{
		$file.Writeline("`t" * $tabCount + "<terms>");
	}

	if ($level -ge 1 -or $level -le 7)
	{
		if ($terms.Count -gt 0 ) {
			$termSetName = ""
			if ($level -eq 1) {
				$termSetName =  """" + $terms[0].TermSet.Name.Replace([System.Text.Encoding]::UTF8.GetString($amp), "&") + """"
			}
			$terms | ForEach-Object {
				$termName = $_.Name.Replace([System.Text.Encoding]::UTF8.GetString($amp), "&");
				$currentTerms = $previousTerms + ",""" + $termName + """";

				$file.Writeline("`t" * $tabCount + "`t<term Name='" + $termName + "' isAvailableForTagging='" + $_.IsAvailableForTagging + "'>");
				$file.Writeline("`t" * $tabCount + "`t`t<description>" + $_.GetDescription() + "</description>");

				if ($level -lt 7) {
					Export-SPTermSet $_.Terms ($level + 1) ($previousTerms + $currentTerms)
				}
				$file.Writeline("`t" * $tabCount + "`t</term>");
			}
		}
	}

	if ($terms.Count -gt 0)
	{
		$file.Writeline("`t" * $tabCount + "</terms>");
	}
}

try {
	Write-Host "Starting export of Metadata Termsets" -ForegroundColor Green
	$ErrorActionPreference = "Stop"
	Add-Snapin

	if (!($exportPath)) {
		$exportPath = (Get-ScriptDirectory)
	}

	Write-Host "Site: $siteUrl" -ForegroundColor Yellow
	Write-Host "Term Group: $termGroup" -ForegroundColor Yellow
	Write-Host "Export Path: $exportPath" -ForegroundColor Yellow

	Export-SPTerms $siteUrl $termGroup $exportPath
}
catch {
	Write-Host ""
    Write-Host "Error : " $Error[0] -ForegroundColor Red
	throw
}
finally {
	Remove-Snapin
}
Write-Host Finished -ForegroundColor Blue

export-terms-xml.ps1 (5.31 kb)

By

SharePoint and PeoplePicker configuration

MSDN Article: http://technet.microsoft.com/en-us/library/gg602075.aspx

Excellent article on complex scenarios: http://blog.octavie.nl/index.php/2010/10/12/my-challenge-with-the-people-picker/

 

Important steps:

1. Set an encryption key for use with a one-way trust

If the forest or domain on which SharePoint 2013 is installed has a one-way trust with another forest or domain, you must first set the credentials for an account that can authenticate with the forest or domain to be queried before you can use the Stsadm peoplepicker-searchadforests property.

Note: The encryption key must be set on every front-end web server in the farm on
which SharePoint 2013 is installed.

To set an encryption key, type the following command:

stsadm.exe -o setapppassword -password <Key>

2. Enable cross-forest or cross-domain queries when you use a one-way trust

If the forest or domain on which SharePoint 2013 is installed has a one-way trust with another forest or domain, you must specify the credentials to be used to query the forest or domain, in addition to the names of the forests or domains to be queried. People Picker will only query the forests or domains that you specify in the peoplepicker-searchadforests property setting.

STSADM.exe -o setproperty -pn peoplepicker-searchadforests
-pv "forest:Contoso.com,ContosoUser1,Password1;domain:Fabrikam.com,FabrikamUser2,Password2"
-url http://central

 

Here are is a sample batch file to help

 

@echo off
setlocal

SET UID=%1
SET PWD=%2

SET PPCFG="domain:corp.domain.org,%UID%,%PWD%;domain:pws.domain1.com,%UID%,%PWD%;domain:domain2.lab,%UID%,%PWD%"

CALL :execute %PPCFG% <<URL1>>
CALL :execute %PPCFG% <<URL2>>
exit /b

:executeecho Setting People Picker for URL: %2
STSADM.exe -o setproperty -pn peoplepicker-searchadforests -pv %1 -url %2
GOTO:eof

 

Attached script:

set-peoplepicker.bat (375.00 bytes)