scripted “re creation” of User Profile Service app from powershell as spfarm account after deleting the existing UPSA.

Thanks to Brian Lala and AutospInstaller for the inspiration and start-process syntax.

  • Ensure UAC is OFF
  • Run a PowerShell window as administrator
  • Paste the script below into your.ps1 file and run it
$script = {
Add-PSSnapin microsoft.sharepoint.powershell -ea SilentlyContinue
$upServiceAppName="User Profile Service Application"
$upAppPool="SharePoint Hosted Services"
$upProfileDB=("$prefix" + "_Profile")
$upSyncDB=("$prefix" + "_Sync")
$upSocialDB=("$prefix" + "_Social")
$upMySiteHostUrl=("http://$prefix" + "-mysites." + "$tld" + ":" + "$mshport" + "/")
$upsapp = Get-SPServiceApplication | ? {$_.TypeName -like "User Profile Service Application"}
if($upsapp -eq $null) {
    #write-host "Delete pre existing User Profile timer jobs"
    #Get-SPTimerJob | where {$ -match "User Profile Service.*"} |  % {
    #    write-host "deleting timer job:" $_.Name
    #    $_.Delete()
    # }
    write-host "Create UPSA"
    try {
        $upsapp = New-SPProfileServiceApplication `
                    -ApplicationPool $upAppPool `
                    -MySiteHostLocation $upMySiteHostUrl `
                    -Name $upServiceAppName `
                    -ProfileDbName $upProfileDB `
                    -ProfileDbServer $upProfileDbServer `
                    -ProfileSyncDbServer $upSyncDbServer `
                    -ProfileSyncDbName $upSyncDB `
                    -SocialDbName $upSocialDb `
                    -SocialDbServer $upSocialDbServer
        if($setNetbiosName) {
            write-host "Enable NETBIOS domain names"
    catch {
        write-host $_
else {
    write-host "Pre existing User Profile Service Application"
if($upsapp -ne $null) {
    write-host "Create UPSA Proxy"
    $upsAppProxy = Get-SPServiceApplicationProxy | ? {$_.TypeName -like "User Profile Service Application Proxy"}
    if($upsAppProxy -eq $null) {
        try {
            $upsAppProxy = New-SPProfileServiceApplicationProxy `
                            -ServiceApplication $upsapp.Id `
                            -Name $upServiceAppName
        catch {
            write-host $_
else {
    write-host "Pre existing UPSA Proxy"
# this runs the script defined above under spfarm user account
# orginally sourced from Brian Lala autoSP-Installer for the "Start-process" syntax, Thanks Brian :-)
# See Brian T if it does not work for you
$secpasswd = ConvertTo-SecureString "p@55w0rd" -AsPlainText -Force
$farmCredential = New-Object System.Management.Automation.PSCredential ("domain\spfarm", $secpasswd)
$scriptFile = "$env:TEMP\UPCreate-Script.ps1"
write-output $script | out-file $scriptFile
Start-Process  -WorkingDirectory $PSHOME -FilePath "powershell.exe" -Credential $farmCredential -ArgumentList "-Command Start-Process -WorkingDirectory `"'$PSHOME'`" -FilePath `"'powershell.exe'`" -ArgumentList `"'$scriptFile'`" -Verb Runas " -Wait
$msg = "UP SA Creation done`n`n"
$msg += "You need to start the UP Sync service in `"Services on a server`"`n"
$msg += "Create a Sync connection, if you get error in create, try to use a new name for connection`n"
$msg += "Ensure UP Service account has Admin and full control of UP SA`n"
$msg += "Ensure msh app pool account has Admin and full control of UP SA`n"
$msg += "Ensure app pool account has Admin and full control of UP SA`n"
$msg += "Ensure sp content account has Admin = read people data in UP SA`n"
$msg += "Ensure sp farm account has Admin and full control of UP SA`n"
$msg += "Ensure setup (you) account has Admin and full control of UP SA`n"
$msg += "Configure service application associations and ensure UP SA is associated"
$msg += "Run a full sync`n"
write-host $msg

SharePoint 2013 Managed Metadata Service – Issue

This may happen to you, if it does this may help.

Deployed March public update to my farm, this caused the Managed Metadata service to not be able to connect from either central admin or a site collection site settings pages.

It claimed the service not running or app pool not started see your administrator, message in a red square box on termstore management pages ….

Now this is all working fine prior to March PU (I know it is true, I have check points I revert to and check) so this is very odd.

Well, you could just delete the MMS and re create your term stores manually ? well, no, some internal stuff in SharePoint used the unique id of terms and termsets internally, if you delete and recreate the MMS the terms and termsets will have new id’s so the internal plumbing will break.

So, in my case the PowerShell commands;


Still allowed me to access the MMS data (Really odd ?????) even though the SharePoint UI would not.


  • Export the MMS to file, on the app server
  • e.g Export-SPMetadataWebServicePartitionData -Identity “” -Path “c:\software\” -ServiceProxy “Managed metadata service”
  • Delete the original MMS (Include data) in central admin
  • Recreate MMS with exactly same names and app pool in central admin
  • Copy exported CAB file to a share on the SQL box
  • Run the import on the app server
  • e.g. Import-SPMetadataWebServicePartitionData -Identity” -Path “c:\software\” -ServiceProxy “Managed metadata service” -OverwriteExisting:$true

Chances are the import will fail, Make sure MMS service account has BULK ADMIN rights in SQL and in a multi server farm you must put the export file on your SQL box in a shared (everyone full control) folder, and on the app server refer to it via UNC in the import command.

Happy days, Metadata is back and seems internally to be good as new.


SharePoint 2013 – Workflow – FBA – Journey (on-prem)

If you are getting these 🙂

Retrying last request. Next attempt scheduled in less than one minute. Details of last request: HTTP Unauthorized to

You may need this

Setting up SharePoint 2013 workflow is documented all over the internet, not all on one page though 🙂

This is how I got it all to work

Start here

  • Follow religiously this set of videos
  • Once configured enable site feature ‘WorkflowServiceStore’ use powershell Enable-SPFeature WorkflowServiceStore -Url http://yoursite
  • Now in the UI activate feature on your site ‘workflow can use app permissions’
  • Now grant full control to workflow ‘workflow’
  • wrap any steps of your workflow which fail for prmission related stuff in an “App step”

Simple eh ?

I guess we owe this complexity to SharePoint online and Office 365 (The future don’t you know)

Managed metadata service – not permissions

Well, this is a good one

Can access Managed metadata service in Central admin -> Manage service apps but not from the site itself.

Try this

Set the app pool for the site temporarily to run as the Farm account
Load site term store manager, it should now load
now …
Switch the site app pool back to SPAppPool or whatever it was
Load site term store manager, it should still load

My explanation is, Black magic and voodoo 🙂

Where does RDCMan keep its list of “Files to open” and other addvice

Took a while to find this

On windows 7
C:\Users\yourUserName\AppData\Local\Microsoft Corporation\Remote Desktop Connection Manager\RDCMan.settings

  • If you want to group your VMs, create a RDCMan file, add a group, then Add servers to groups, don’t add servers lose to a file, or drag and drop gets screwed up.
  • If you have a server lose in a file you will not be able to create a group in that file in the UI or via drag drop.

Probably by design 🙂

BT Homehub 3A and Port Forwarding

Recently went over to the dark side and switched my broadband provider from Virgin Media to BT.

To cut a long story short (bad that they failed to get the installation right first time, applause for the customer service to put it right afterwards.  Could be easier to find a way to get in touch by email off the web site, big kudos for the support girl who called me on Sunday morning to ask if it was all sorted now.)

So port forwarding on the bt home hub 3A, at first glance seems not to work.  It goes like this.  you plug in the hh3A and your devices will request an ip address at their next reboot or renewal, either way, the hh3A assigns each device an ip address from its own address pool.

At the same time (and this is the issue) it gathers the name of the devices and records them internally so you have an easy time deciding which is which.

Now when you configure the port forwarding, the device names are what you use to decide what traffic goes to each device.

At this stage port forwarding is all set up, it fails to forward any traffic though, perhaps because it cannot resolve the device names that it assigned earlier.

For me the fix was to rename each device inside the hh3A to be it’s IP address, I also made the ip address allocations static so each device will keep the ip address I have assigned for all time.

So, port forwarding on hh3A does work, just need a little effort.

Build a SharePoint 2013 VM

Use SQL 2012 and Windows 2012 using Brian Lala autospinstaller

New VMWare workstation 8 Vm (8 gig ram and 60 gig HD)
Use Windows 2008 R2 template – enable video acceleration

Install W2k12 Server – Standard
Enable RDP, hereafter everything over RDP

Rename-Computer SP2013

Make IP address static

Install-WindowsFeature AD-Domain-Services -IncludeManagementTools
Install-ADDSForest -DomainName yourDomain.local

Create user Account
Add user to Domain admins, Enterprise admins

Log off domain admin, log in as user
Confirm IE 10.0 can see outside world

Create Base OS and AD checkpoint

Power on
Login as user
Windows updates (7 updates)
Turn off UAC

Install SQL 2012 (SP1)

SQL Config – All protocals enabled
Restart SQL svc
Windows updates (2 updates)
Shut down
Create Post SQL checkpoint
DAY 2 (4 attempts on this)
Power on
create AutoInstallerInput-SP2013.xml on shared drive from host machine ( I used CMSPUBLISHING#0 as portal app template)

Edit config.xml and put in correct PIDKEY
put SharePoint media here as per Brian Lala docs

CMD window as admin
wscript /H:cscript
net use Z: \\\d$ /user:yourdomain\user
Z:\CommonShare\autospinstaller-v3\createserviceaccounts.vbs (ask me if you need this)
Move users using AD tools to Services OU
CD \CommonShare\autospinstaller-v3\SP\AutoSPInstaller
Made server reboot to do UAC even though UAC was already off – prereq requires a reboot
Made server reboot to do UAC even though UAC was already off – ANOTHER prereq requires a reboot
– publishing site icons all showing ??? (Fixed by switching masterpage from seattle to oslo – leave system master at seattle)
– Create a non publishing site /sites/t1 icons fine here
Checkpoint PostFarm

From Spence Harbar blog:
We need to grant the Replicating Directory Changes permission on the domain to the DOMAIN\spups account. This account will be used to perform the sync, it will not run any services or application pools.

Right Click the Domain, choose Delegate Control… click Next
Add the DOMAIN\spups account, click Next
Select Create a Custom Task to Delegate, click Next
Click Next
Select the Replicating Directory Changes permission and click Next
Click Finish

Skipped rest of Spences instructions as dont pertain to a domain controller, which this is (even though that is a bad thing)


Build Azure infrastructure using PowerShell

  • Install VS 2012 premium
  • Install Azure SDK
  • Install Azure PowerShell CmdLets
  • Download and convert to latest SIteMonitR – I am using this excellent article to run on my auto created Azure Infrastructure.  You can get it from
  • See PowerShell code below to create or re-create infrastructure on Azure, which you will need to run prior to deploying your application. Also, anytime you trash and re-create your infrastructure on Azure, re-do the deployment steps including downloading the publishing files as they will be different each time you generate the infrastructure

So these are the steps

  • Run createAzureInfrastructureForLab.ps1
  • Confirm Storage account, cloud service and Web site are created
  • Now follow instructions from relevant ones reproduced below

Load project into VS, May require converting and references updating to latest versions of Azure SDK, VS will take care of all these steps

Go into the dashboard for the new storage account you created and click the Manage Keys button at the bottom of the portal. Copy the storage account’s key to the clipboard.

In Visual Studio 2012, expand the SiteMonitR.Azure project’s Roles node. Double-click the SiteMonitR.WorkerRole node to open up the role’s settings pane.
Select the Cloud option from the Service Configuration drop-down menu.
Click the ellipse button next to the SiteMonitRConnectionString setting.
Enter in the storage account name and primary access key copied from the portal.
Click the OK button.

Repeat the same steps to set the Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString setting.
Change the GUI_URL setting to reflect the URL of the Windows Azure Web Site you created using the Windows Azure portal.

Right-click the SiteMonitR.Azure project and select the Publish menu item from the context menu.
If you haven’t yet imported your publish settings, click the Sign in to download credentials link in the publish dialog.
Your web browser will open up and browse to the Windows Azure publish profile download page. When the page tries to download the publish settings file, click the Save button to save the file to your local workstation.
Go back to Visual Studio 2012. Click the Import button in the publish dialog. Then, browse to the publish settings file you just downloaded and select it.
Click the Publish button to deploy the Cloud Service to Windows Azure.
The Windows Azure Activity Log window should open to display the Cloud Service’s publishing process happening.

Go back to the Windows Azure portal. Click the web site you just created to load the site’s dashboard page.
Once the site’s dashboard loads in the browser, click the Download publish profile link.
When the browser tries to download the file, save it to your local workstation.
Right-click the SiteMonitR.Web project in Visual Studio 2012. Then select the Publish menu item from the context menu.
Click the Import button on the publish dialog. Then, find the web site publish settings file downloaded from the Windows Azure portal.
Click the Publish button in the dialog to publish the web site to Windows Azure.

Once the site has been published, go back to the site’s dashboard page in the Windows Azure portal. Click the Configure tab.
Change the default document from Default.htm to Default.html. Then delete the other options from the list of default pages. Then, click the Save button to save the site configuration.

Click the Browse button at the bottom of the web site’s dashboard to browse the site.

The site will open and present you with a simple form you can use to provide URL’s of sites you’d like to monitor.

Type in a site URL and click the Add Site button. The site will be added to the list of sites you are monitoring.
Add in as many sites as you would like. All of the sites are monitored by the Cloud Service. Their status will update in real-time as the sites are hit by the service and reported in the web site. To remove a site, click the X button and the site will be removed from the list of sites monitored by the application.

######### Put this into a powershell file, say createAzureInfrastructureForLab.ps1
$errorActionPreference = 'Stop'
try {
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\Azure\Azure.psd1" -ErrorAction silentlycontinue
catch {
write-host "Module already present"
$Location="West Europe"
# ---
$MonitorWebSiteName = "YourMonitorSite"
# --- Get next lot of stuff from Azure dashboard for your account
$mySubID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$certThumbprint = "40 digit thumbprint"
$myCert = Get-Item cert:\CurrentUser\My\$certThumbprint
$mySubName = "Name of your Azure subscription"
Set-AzureSubscription -SubscriptionName $mySubName -Certificate $myCert -SubscriptionID $mySubID
Select-AzureSubscription -SubscriptionName $mySubName
try {
$ws = get-AzureWebsite -Name $MonitorWebSiteName
try {
Remove-AzureWebsite -Name $MonitorWebSiteName -Force:$true -Confirm:$False
catch {
write-host $_
write-host "Remove web site $MonitorWebSiteName failed."
catch {
write-host "Web site $MonitorWebSiteName not present."
try {
$svc = get-AzureService -ServiceName $monitorCloudServiceName
try {
Remove-AzureService -ServiceName $monitorCloudServiceName -Force:$true -Confirm:$False
catch {
write-host $_
write-host "Remove Cloud service $monitorCloudServiceName failed."
catch {
write-host "Cloud service $monitorCloudServiceName not present."
try {
$sa = Get-AzureStorageAccount -StorageAccountName $storageAccountName
try {
Remove-AzureStorageAccount -StorageAccountName $storageAccountName
catch {
write-host $_
write-host "Remove storage account $storageAccountName failed."
catch {
write-host "Storage account $storageAccountName not present."
Read-host "Check it as all gone. Then press ENTER to re-create it all"
# NADA NOW !!!!!!!
# create new bits here
try {
New-AzureStorageAccount `
-StorageAccountName $storageAccountName `
-Description $storageAccountName `
-Location $Location
write-host "Storage account created."
catch {
write-host $_
write-host "Storage account create failed.."
try {
New-AzureService `
-ServiceName $monitorCloudServiceName `
-Description $monitorCloudServiceName `
-Location $Location
write-host "Cloud service created."
catch {
write-host $_
write-host "Cloud service create failed."
try {
New-AzureWebsite `
-Name $MonitorWebSiteName `
-Location $Location
write-host "Web site created."
catch {
write-host $_
write-host "Web site create failed."
Set-AzureSubscription -SubscriptionName $mySubName -Certificate $myCert -SubscriptionID $mySubID -CurrentStorageAccount $storageAccountName
Select-AzureSubscription -SubscriptionName $mySubName

Setting super user / super reader account

This is the resolution to some tedious event log errors, which should be resolved.

add-pssnapin microsoft.sharepoint.powershell -erroraction silentlycontinue
function SetSuperCacheUsers()
param (
    [string] $webApp,
    [string] $prefix,
    [string] $superuser,
    [string] $superreader
    $wa = Get-SPWebapplication -identity $webApp
    $wa.Properties["portalsuperuseraccount"] = ($prefix + $superuser)
    $wa.Properties["portalsuperreaderaccount"] = ($prefix + $superreader)
SetSuperCacheUsers  -webApp "" `
                    -prefix "i:0#.w`|" `
                    -superuser "escape\SPObjCacheSuper" `
                    -superreader "escape\SPObjCacheRead"
write-host "Now you should ensure that the accounts you set here have appropriate access in web App User Policy"
write-host "in central admin, Full control for the Super user and Full Read for the super reader"