Below is a way to run userprofile service through powershell. This script wait for the completion of user profile service execution and let user know when it completes.
param(
[string]$siteUrl
)
function RunUserProfileSynchronization()
{
try
{
$site= New-Object Microsoft.SharePoint.SPSite($siteUrl)
$serviceContext = [Microsoft.SharePoint.SPServiceContext]::GetContext($site)
$configManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileConfigManager($serviceContext)
if($configManager.IsSynchronizationRunning() -eq $false)
{
[DateTime] $lastoverallendtime= $configManager.GetSynchronizationStatus().LastOverallEndTime;
Write-Host "Starting user profile synchronization"
$configManager.StartSynchronization($false);
Write-Host "User Profile synchronization is started"
Write-Host "########################################################################";
while($true)
{
Write-Host "Please wait it is still running............. "
if($configManager.GetSynchronizationStatus().LastOverallEndTime -ne $null)
{
# Below wait period is important to avoid SQL query threshhold
Start-Sleep -s 10
if ($configManager.GetSynchronizationStatus().LastOverallEndTime -gt $lastoverallendtime)
{
Write-Host "Synchronization service completed below is overall status:- "
Write-Host "Lastoverallstarttime" $configManager.GetSynchronizationStatus().LastOverallStartTime;
Write-Host "Lastoverallendtime " $configManager.GetSynchronizationStatus().LastOverallEndTime;
Write-Host "Overallfailure" $configManager.GetSynchronizationStatus().OverallFailures;
Write-Host "Overallsuccess" $configManager.GetSynchronizationStatus().OverallSuccesses;
break;
}
}
else
{ # Below wait period is important to avoid SQL query threshhold
Start-Sleep -s 10
}
}
}
else
{
Write-Host "Already Synchronizing"
}
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Host ($ErrorMessage) -ForegroundColor Red
}
}
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null)
{
Write-Output "Loading SharePoint Powershell Snapin" -ForegroundColor Green
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}
RunUserProfileSynchronization