Powershell: How to restart the User Profile Synchronization Service if disabled?

Below script shows how to restart the User Profile Synchronization Service if disabled.



# Loads the SharePoint 2010 PowerShell extensions
Add-PSSnapIn Microsoft.SharePoint.PowerShell 

# Sets variable for User Profile Service Application: enter the name of your UPA in quotes, replacing the "UPA" example
$upa = Get-SPServiceApplication |?{$_.displayname -eq "UPA"}

# Sets variable for service instance: enter your User Profile Synchonization Service instance ID/GUID in quotes
# which can be found by running "Get-SPServiceInstance" in PowerShell manually and copying the ID
$profsync = Get-SPServiceInstance |?{$_.id -eq "382e333c-61f0-4107-ac5f-31aaf0a3aec3"}

# Sets variables for farm account and password: enter your password in quotes
$farmacctpwd = ConvertTo-SecureString -AsPlainText -String "Password1" -Force
$farmacct = (get-spfarm).defaultserviceaccount

# Sets variable for synchronization server: enter your server name in quotes
$syncServer = "SharePoint1"
if($profsync.Status -eq "disabled")
  Write-Host "Provisioning User Profile Synchronization Service"
  $upa.SetSynchronizationMachine($syncServer, $profsync.ID, $farmacct.LookupName(), $farmacctpwd)
  write-host "Profile Synchronization Service is"$profsync.Status