Starting UserProfile service with PowerShell

Ran into something interesting while trying to script out a farm install.  I was trying to generate generic functions to create service applications and start the associated services, and kept hitting issues starting the User Profile Sync service.  The first hurdle you have to jump is that you have to run your PowerShell script as the farm account.  Once you get past that, if you try to use Start-SPServiceInstance to start the Profile Synchronization Service, you will be greeted with the service failing to start.  The SharePoint trace logs and the event viewer will show you the following message:

System.InvalidOperationException: No associated User Profile Application found at Microsoft.Office.Server.Administration.ProfileSynchronizationServiceInstance.Provision() at Microsoft.SharePoint.Administration.SPServiceInstanceJobDefinition.Execute(Guid argetInstanceId)

The message makes sense considering when you start the service from Central Administration you have to select the Service Application the service is associated with.  Looking at the Start-SPServiceInstance cmdlet, there is not a way to specify this information.  Did some digging and our Technet documentation has a PowerShell sample of creating the User Profile Service Application and starting the services

The key to getting the service to start is to use Start-SPServiceInstance on the User Profile Service, then call SetSynchronizationMachine on the User Profile Application object to associate the service with the service application.  If you don’t start the User Profile Service first, the Sync service will fail to start with an event viewer entry stating that the User Profile Service is not started.  The SetSynchronizationMachine call will start the User Profile Synchronization service, so there is no need to call Start-SPServiceInstance after.

[Update - 01/08/2011] Spencer Harbar has a blog showing how to run the UserProfile provisioning script following least privilege practices.