Showing posts with label SharePoint 2010. Show all posts
Showing posts with label SharePoint 2010. Show all posts

Wednesday, 18 February 2015

PowerShell to do restructuring of SharePoint content

You might have went through scenario where most SharePoint implementations have outgrown the original purpose for which they were designed at initials – what might was envisioned as a simple solution has now become a complex environment. This has resulted your complex environment - one that is constantly undergoing changes in content and usability. However, in spite of these changes, SharePoint continues to cater to the growing and varied needs of the organization. As a result, there is a continuous need for periodic restructuring of content and metadata.

In market you would find many 3rd party tool to done this job, but each of them will require license and this is what lenthy process to bring in operation. You have a great handy tool available to do this job, powerShell.

You can use the Export-SPWeb and Import-SPWeb cmdlets to move heavy subsites to new destination or can even restructure URL:

Import-SPWeb:
http://technet.microsoft.com/en-us/library/ff607613(v=office.14).aspx
Export-SPWeb:
http://technet.microsoft.com/en-us/library/ff607895(v=office.14).aspx

The general syntax of these commands are:

Export-SPWeb [-Identity] <url of the site to be exported> -Path <location and name of the file to be created after export> [-Force] [-IncludeUserSecurity] [-IncludeVersions <LastMajor | CurrentVersion | LastMajorAndMinor | All>] [-ItemUrl <Any specific item to export, like document library or list>]
Import-SPWeb [-Identity] <url of the site to be exported> -Path <location and name of the file to be imported from> [-Confirm] [-Force] [-IncludeUserSecurity] [-UpdateVersions <Append | Overwrite | Ignore>]
You can use the IncludeUserSecurity parameter to export the associated security with the site, library, or list which includes users in the site, authors of documents and lists, when the document or list was created and modified, etc... and the IncludeVersions parameter to specify which versions of the documents or list items you want to export, whether to export current versions, last major versions, last major or minor versions or all versions, etc.

  • If your SQL Server version supports database snapshot (Enterprise and Developer editions) , it is recommended to use UseSqlSnapshot parameter with Export-SPWeb command for a more consistent backup. 
  • Workflows are not included when we export/import contents of sites, libraries, or lists.
Valid migration scenarios when using the Publishing features are the following:
  • Export the site collection starting at the root site and then import it as the root site into a new site collection
  • Export subsites of the site collection and then import them as subsites into an existing site collection that has the Publishing features enabled
Some manual work may be required to ensure master pages and page layouts that are in use in the subsites are copied over to the new site collection.

If your environments have customizations, such as custom template you might receive error as below while import

[2/12/2014 3:14:51 PM]: Progress: Initializing Import.
[2/12/2014 3:15:08 PM]: FatalError: Could not find WebTemplate #10011 with LCID 1033. at Microsoft.SharePoint.Deployment.ImportRequirementsManager.VerifyWebTemplate(SPRequirementObject reqObj) at Microsoft.SharePoint.Deployment.ImportRequirementsManager.Validate(SPRequirementObject reqObj) at Microsoft.SharePoint.Deployment.ImportRequirementsManager.DeserializeAndValidate() at Microsoft.SharePoint.Deployment.SPImport.VerifyRequirements() at Microsoft.SharePoint.Deployment.SPImport.Run() [2/12/2014 3:15:14 PM]: Progress: Import Completed. [2/12/2014 3:15:14 PM]: Finish Time: 2/2/2014 3:15:14 PM. [2/12/2014 3:15:14 PM]: Completed with 0 warnings. [2/12/2014 3:15:14 PM]: Completed with 1 errors.

Use below script to check available webtemplates in the farm or in target farm if you moving to another farm.
get-spwebtemplate | select name,title,id

If any of the missing template(10011) does not exist in target farm, you will need to install those features in farm .

Change SharePoint Farm account

Change SharePoint Farm account
 
Use this powershell script if you would like to replace an existing managed account credential
Introduction
 
Use this powershell script if you would like to replace an existing managed account credential with new managed account. That applies also to the farm admin user. The PowerShell script will scan the following items and replace user account accordingly:
 
• 1- SharePoint Services
• 2- SharePoint Service Applications App Pools
• 3- SharePoint Web application App Pools
 
and there is an extra function added "UpdateFarmCredentials" to update the farm credentials if the need be.
 
I would recommend resetting the IIS after running this script.
 
How to use the script
 
You need to run this script in an elevated command prompt screen from one of the SharePoint servers of the targeted farm running with the farm admin account.
 
At the end of the file make sure you replace the following variables with your desired values:
• 1- $OldUser (The old managed account you want to replace)
• 2- $NewUser (The new managed account you want to register and use)
• 3- $NewUserPassword (The new managed account password)
 
Please note
 
• The script might throw some warnings when you try to use a local account in a farm deployment. You can ignore these warning however, you should know that it’s not recommended to use local accounts. You might also see some errors regarding deploying some of the changes to some of the Service applications. You can ignore these errors as well.
  • The script will register the new managed account for you if it’s not registered yet and will prompt you for the password to be stored in SharePoint.
• This script is written and test on SharePoint 2010 version only.
• Some users reported that the UPA stopped working after replacing the credentials.
 
Run this script at your own risk
 
 
 
 
function UpdateFarmCredentials($userName,$Password)
{
    #Prepare Stsadm to be used through powershell
    Set-Alias -Name stsadm -Value $env:CommonProgramFiles"\Microsoft Shared\Web Server Extensions\14\BIN\STSADM.EXE"
    $Command = "stsadm -o updatefarmcredentials -userlogin '$userName' -password '$Password'"
    trap{"Error updating farm credentials"}
    Invoke-Expression $Command
}
function Ensure-SPAccount($userName)
{
    #Add SharePoint Snap-in
    if((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
    {
        Add-PSSnapin Microsoft.SharePoint.PowerShell;
        Write-Host "SharePoint PowerShell Snap-In added";
    }
    if(Get-SPManagedAccount | Where-Object { $_.UserName -eq $userName }){
      # Managed Account Already exists
      Write-Host “Managed Account: $userName exists”
    } else {
      # Get User Credentials
      $credential = Get-Credential -Credential $userName
      # Create New Managed Account
      New-SPManagedAccount -Credential $credential
    }
}
function Get-SPServiceIdentity()
{
    #Add SharePoint Snap-in
    if((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
    {
        Add-PSSnapin Microsoft.SharePoint.PowerShell;
        Write-Host "SharePoint PowerShell Snap-In added";
    }
    foreach ($ser in Get-SPServiceInstance)
    {
        $T = $ser.GetType()
        if($T.BaseType.Name -like "SPWindowsServiceInstance")
            {
                Write-Host "Service= " $ser.TypeName ", Identity=" $ser.Service.ProcessIdentity.UserName
            }
    }
}
function Replace-SPServiceIdentity($FromUser,$ToUser)
{
    #Add SharePoint Snap-in
    if((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
    {
        Add-PSSnapin Microsoft.SharePoint.PowerShell;
        Write-Host "SharePoint PowerShell Snap-In added";
    }
    $fromUserLower = "$FromUser"
    $fromUserLower = $fromUserLower.ToLower().Trim()
   
    #Make sure Service account is added
    Ensure-SPAccount $ToUser
   
    foreach ($ser in Get-SPServiceInstance)
    {
        $T = $ser.GetType()
        if($T.BaseType.Name -like "SPWindowsServiceInstance" -and $ser.Service.ProcessIdentity.UserName -ne $null)
        {
            $UserName = $ser.Service.ProcessIdentity.UserName.ToLower()
            if($UserName -Like $fromUserLower)
            {
                Write-Host "Updating Service= " $ser.TypeName
                $ser.Service.ProcessIdentity.UserName = $ToUser
                $ser.Service.ProcessIdentity.Update()
                $ser.Service.ProcessIdentity.Deploy()
            }
           
        }
    }
}
function ReplaceServiceAppsApplicationPoolIdentity($FromUser,$ToUser)
{
    #Add SharePoint Snap-in
    if((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
    {
        Add-PSSnapin Microsoft.SharePoint.PowerShell;
        Write-Host "SharePoint PowerShell Snap-In added";
    }
   
    $fromUserLower = "$FromUser"
    $fromUserLower = $fromUserLower.ToLower().Trim()
   
    #Make sure Service account is added
    Ensure-SPAccount $ToUser
   
    #Replace service apps application pool identities
    foreach($appPool in Get-SPServiceApplicationPool)
    {
        if($appPool.ProcessAccountName.ToLower() -Like $fromUserLower)
        {
            Write-Host "Updating" $appPool.Name "..."
            Set-SPServiceApplicationPool  $appPool –Account $ToUser
        }
    }
   
}
function ReplaceWebAppsApplicationPoolIdentity($FromUser,$ToUser)
{
    #Add SharePoint Snap-in
    if((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
    {
        Add-PSSnapin Microsoft.SharePoint.PowerShell;
        Write-Host "SharePoint PowerShell Snap-In added";
    }
    
    $fromUserLower = "$FromUser"
    $fromUserLower = $fromUserLower.ToLower().Trim()
   
    #Make sure Service account is added
    Ensure-SPAccount $ToUser
   
    #Replace web apps application pool identities
    foreach($WebApp in Get-SPWebApplication)
    {
        $appPool = $WebApp.ApplicationPool
        if($appPool.ManagedAccount.UserName.ToLower() -Like $fromUserLower)
        {
            Write-Host "Updating '" $WebApp.Url "' web app applicaiton pool identity..."
            $id = Get-SPManagedAccount $ToUser
            $appPool.ManagedAccount = $id
            $appPool.Update()
        }
    }
   
}
 
 
$OldUser= "rk\spmanagedac1"
$NewUser = "rk\spmanagedac1"
$NewUserPassword = "password01"
#UpdateFarmCredentials $OldUser $NewUserPassword
Replace-SPServiceIdentity $OldUser $NewUser
ReplaceServiceAppsApplicationPoolIdentity $OldUser $NewUser
ReplaceWebAppsApplicationPoolIdentity $OldUser $NewUser

Saturday, 10 January 2015

How to Remove a SharePoint WFE/Application server from an existing farm?

You can find two methods in TechNet or other blogs to remove a SharePoint 2007/2010/2013 server from an existing farm. These methods are through central admin (Remove Server in servers in farm) and through control panel (uninstall SharePoint binaries).

I will suggest, if anybody is ever planning on Uninstalling/Removing a server from a SharePoint Farm, do not go to “Servers in farm” and click “Remove Server” or directly uninstall SharePoint on the server through Control Panel. This will cause failures in timer job status and will cause some problems down the road.

The best approach to uninstall or Remove a server is as follows
  1. Log on to the server you want to remove or uninstall from the farm
  2. Run the SharePoint Products Configuration Wizard
  3. Select “Disconnect from Farm” and click on next
  4. Click OK to continue the wizard


The wizard will take you through the steps and you should be see the “Successful Message”

Now you can uninstall SharePoint binaries from the server disconnected from the Farm.

Wednesday, 7 January 2015

SharePoint: Unable to Upload Multiple Documents Using Internet Explorer

Various SharePoint versions may show different error message while user trying to upload multiple files. Always try to keep all your system updated with latest patches and fixes released by Microsoft.

Problem 1:

I have been reported many times in last few years that SharePoint users are running into a problem where they couldn't upload multiple files in a document library of SharePoint 2010 or 2013 site using “Upload multiple files” or “Open with windows explorer”. When they clicking on the link “Upload files using Windows Explorer” instead from the “Upload document” or “add document” control, they getting below error message: “Your client does not support opening this list with Windows Explorer”.

Solution

Few SharePoint Controls including ‘Open with windows explorer’ dependent on ‘Webclient’ service of Windows OS.
1.  Follow the appropriate step for your operating system: 
 
·   For Windows XP, Windows Vista, and Windows 7, click Start, click Run, type services.msc, and then press Enter.
·   For Windows 8, click Start, type services.msc, and then press Enter.
·   For Windows Server 2008 or Windows Server 2012, click Start, type services.msc, and then press Enter. If the WebClient service isn't present, you must first install the Desktop Experience. For more info about how to install the Desktop Experience, see the following Microsoft website:
(http://technet.microsoft.com/en-us/library/cc754314.aspx)
2.  In the list of services, locate the WebClient service, and then make sure that its status in the Status column is set to Started. If it isn't set to Started, double-click the WebClient service to open the WebClient Properties window, click Start, and then click OK.

Note If the Startup Type for the WebClient service is set to Disabled, the Open with Explorer button won’t function correctly and you'll be unable to start the service. To enable the service, within the WebClient Properties dialog box, click the drop-down dialog for the Startup type: setting and then select either Manual or Automatic. After you complete this step, click Apply, click Start to start the service, and then click OK.
 

Problem 2:

We're having a problem opening this location in File Explorer. To open with File Explorer, you’ll need to add this site to your Trusted Sites list and select the “Keep me signed in” check box when you sign in to the SharePoint Online site. For more information, see http://support.microsoft.com/kb/2629108.

My environment is: - Windows 7 and IE 8 32-bit

Solution

 
Make sure that the SharePoint Online URLs have been added to your Trusted sites zone in Internet Explorer. To do this, follow these steps:
  1. Start Internet Explorer
  2. Depending on your version of Internet Explorer, take one of the following actions:
    • Click the Tools menu, and then click Internet options.
    • Click the gear icon, and then click Internet optionsClick the Security tab, click Trusted sites, and then click Sites.
  3. Click the Security tab, click Trusted sites, and then click Sites. 
  4. In the Add this website to the zone box, type the URL for the SharePoint Online site that you want to add to the Trusted sites zone, and then click Add. For example, type https://contoso.sharepoint.com. (Here, the placeholder contoso represents the domain that you use for your organization.) Repeat this step for any additional sites that you want to add to this zone.
  1. After you have added each site to the Websites list, click Close, and then click OK.
 




Wednesday, 27 November 2013

Clearing the SharePoint Configuration Cache

Error message when you try to modify or to delete an alternate access mapping in Windows SharePoint Services 3.0: "An update conflict has occurred, and you must re-try this action"


To resolve this issue, clear the file system cache on all servers in the server farm on which the Windows SharePoint Services Timer service is running. To do this, follow these steps:
1.       Stop the Timer service. To do this, follow these steps:
a.       Click Start, point to Administrative Tools, and then click Services.
b.       Right-click Windows SharePoint Services Timer, and then click Stop.
c.        Close the Services console.
2.       On the computer that is running Microsoft Office SharePoint Server 2007 and on which the Central Administration site is hosted, click Start, click Run, type explorer, and then press ENTER.
3.       In Windows Explorer, locate and then double-click the following folder:
Drive:\Documents and Settings\All Users\Application Data\Microsoft\SharePoint\Config\GUID
Notes
o    The Drive placeholder specifies the letter of the drive on which Windows is installed. By default, Windows is installed on drive C.
o    The GUID placeholder specifies the GUID folder.
o    The Application Data folder may be hidden. To view the hidden folder, follow these steps:
1.       On the Tools menu, click Folder Options.
2.       Click the View tab.
3.       In the Advanced settings list, click Show hidden files and folders under Hidden files and folders, and then click OK.
o    In Windows Server 2008, the configuration cache is in the following location:
Drive:\ProgramData\Microsoft\SharePoint\Config\GUID
4.       Back up the Cache.ini file.
5.       Delete all the XML configuration files in the GUID folder. Do this so that you can verify that the GUID folder is replaced by new XML configuration files when the cache is rebuilt.

Note When you empty the configuration cache in the GUID folder, make sure that you do not delete the GUID folder and the Cache.ini file that is located in the GUID folder.
6.       Double-click the Cache.ini file.
7.       On the Edit menu, click Select All.
8.       On the Edit menu, click Delete.
9.       Type 1, and then click Save on the File menu.
10.    On the File menu, click Exit.
11.    Start the Timer service. To do this, follow these steps:
 .         Click Start, point to Administrative Tools, and then click Services.
a.       Right-click Windows SharePoint Services Timer, and then click Start.
b.       Close the Services console.
Note The file system cache is re-created after you perform this procedure. Make sure that you perform this procedure on all servers in the server farm.
12.    Make sure that the Cache.ini file has been updated. For example it should no longer be 1 if the cache has been updated.
13.    Click Start, point to Programs, point to Administrative Tools, and then click SharePoint 3.0 Central Administration.
14.    Click the Operations tab, and then click Timer job status under Global Configuration.
15.    In the list of timer jobs, verify that the status of the Config Refresh entry is Succeeded.
16.    On the File menu, click Close.


Thursday, 21 November 2013

Move Files and Folders to another Document Library or list in SharePoint 2010

Move Files and Folders to another Document Library  or list in SharePoint 2010









        private static void Main(string[] args)
        {
            SPSite siteColl = new SPSite("http://riponkundu/abc/");
            SPWeb site = siteColl.OpenWeb();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID))
                {
                    using (SPWeb web = ElevatedsiteColl.OpenWeb(site.ID))
                    {
                        web.AllowUnsafeUpdates = true;
                        string listSrc = "My Documents";
                        string listDest = "My Documents Arc";
                        SPList sourceList = web.Lists.TryGetList(listSrc);
                        SPList targetList = web.Lists.TryGetList(listDest);
                        if (sourceList != null)
                        {
                            SPQuery query = new SPQuery();
                            query.Query = @"<Where><And><IsNotNull><FieldRef Name='ID' /></IsNotNull><Neq><FieldRef Name='ContentType' /><Value Type='Computed'>Folder</Value>
         </Neq></And></Where><QueryOptions><ViewAttributes Scope='RecursiveAll' /></QueryOptions>";
                            query.ViewAttributes = "Scope='RecursiveAll'";
                            SPListItemCollection coll = sourceList.GetItems(query);
                            for (int i = 0; i < coll.Count; i++)
                            {
                                SPListItem sourceItem = sourceList.GetItemById(Convert.ToInt32(coll[i]["ID"]));
                               
                                string modTime = sourceItem["Modified"].ToString();
                                string folderName = sourceItem.Web.GetFile(sourceItem.Url).ParentFolder.Name;//folder name
                                string folder = sourceItem.Web.GetFile(sourceItem.Url).ParentFolder.ServerRelativeUrl;//folder URL
                                SPFolder sourceFolder = sourceItem.Folder;
                                string targetPath = targetList.RootFolder.ServerRelativeUrl + "/" + folderName;
                                SPFolder targetFolder = web.GetFolder(targetPath);
                                SPListItem targetItem = targetFolder.Item;

                                if (Convert.ToDateTime(modTime) <= System.DateTime.Now.AddHours(-4))
                                {
                                    #region check for check out item and make in CheckedIn
                                    if (sourceItem.FileSystemObjectType == SPFileSystemObjectType.File)
                                    {
                                        SPFile sourceFile = sourceItem.File;
                                        if (sourceFile.CheckOutStatus != SPFile.SPCheckOutStatus.None)
                                        {
                                            Console.WriteLine(sourceItem.Name);
                                            sourceFile.UndoCheckOut();
                                        }
                                    }
                                    #endregion
                                    if (web.GetFolder(targetPath).Exists==false)
                                    {
                                        SPFolderCollection targetFolderColl = web.Folders;
                                        targetFolderColl.Add(web.Url+"/"+listDest+"/"+folderName);
                                       
                                    }
                                   
                                    SPFolder oFolder = web.GetFolder(listDest);
                                    SPFile file = web.Folders[listSrc].SubFolders[folderName].Files[sourceItem.Name.ToString()];
                                    file.MoveTo(oFolder.Url + "/"+ folderName +"/" + file.Name, true);
                                }
                            }
                          
                        }
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
        }

Sunday, 17 November 2013

Update SharePoint 2010 Farm Credentials Using PowerShell

Update SharePoint 2010 Farm Credentials Using PowerShell



#Input the Managed Account
#If there is only one managed account, the following line could be written as:
#$inputManagedAcct = Get-SPManagedAccount

$inputManagedAcct = Read-Host "Enter managed account as Domain\User" 
#Input the desired new password 
$inputPasswd = Read-Host "Enter new password for managed account" –AsSecureString 
#Change the password for the managed account to the new value 
Set-SPManagedAccount -Identity $inputManagedAcct -NewPassword $inputPasswd



------------------------------------------------------------------------------------------------------------------------------------------------------------       Update after AD Reset    ----------------------------------------------------------------

#Input the Managed Account
#If there is only one managed account, the following line could be written as:
#$inputManagedAcct = Get-SPManagedAccount

$inputManagedAcct = Read-Host "Enter managed account as Domain\User:" 
#Input the Managed Account 
$inputPasswd = Read-Host "Enter password from Active Directory for managed account:" –AsSecureString 
#Change the password in SharePoint for the managed account to the new value 
Set-SPManagedAccount -Identity $inputManagedAcct -ExistingPassword $inputPasswd –UseExistingPassword $true 

SharePoint Search crawling got stuck at stopping or crawlling!!

PowerShell script to set crawl status as idle


You may face issue sometimes in crawl component configuration of SharePoint 2010/2013 Search. If you change any configuration of crawl, you must run full crawl once, or else it will throw error in backup operation. If a crawler is in running state, it will not allow you to change scope or sites url. To set the crawl status of a search service write search service name in below script

Get-SPEnterpriseSearchCrawlContentSource -SearchApplication "Search Service Application" | ForEach-Object {
     if ($_.CrawlStatus -ne "Idle")
     {
         Write-Host "Stopping currently running crawl for content source $($_.Name)..."
         $_.StopCrawl()
        
         do { Start-Sleep -Seconds 1 }
         while ($_.CrawlStatus -ne "Idle")
     }
}









Powershell to restart timer service in Multitier SharePoint Farm

The SharePoint Timer service



As a single unified logical entity, a SharePoint farm requires a mechanism to run tasks necessary to provide its services. These tasks include updating components of the farm such as servers and services, and updating data and configuration in farm databases. To run these tasks, SharePoint provides its own scheduled tasks management service, manifested as Timer Service instances installed on every SharePoint server in the farm. If the Timer Service or any of its instances on servers begins to malfunction, it won't take long for problems to begin appearing across the farm. For all its importance, though, the Timer Service is often misunderstood. In this blog post we'll explore the basic elements and startup process of the SharePoint Timer Service. In the future and as time permits, we'll further explore the Timer Job system and many of the specific Timer Jobs which run in a farm.


Start the timer service:
  1. Verify that the user account that is performing this procedure is a member of the Administrators group on the local computer.
  2. Open a Command Prompt window, type the following command at the command prompt, and then press ENTER:
    net start sptimerv4
  3. If the service does not start, ensure that the service identity account is configured correctly by using the "Verify the service account" procedure later in this article.

Verify the service account:

  1. Verify that the user account that is performing this procedure is a member of the Administrators group on the local computer.
  2. Click Start, click Administrative Tools, and then click Services.
  3. Right-click Windows SharePoint Services Timer V4, and then click Properties.
  4. On the Log On tab, confirm that the account being used is a domain user account and is a member of the following:
    • dbcreator fixed SQL Server server role
    • securityadmin fixed SQL Server server role
    • db_owner fixed database role for all databases in the server farm
  5. If the account has sufficient permissions, confirm the password by typing the password for the account, retyping the password in the Confirm password box, and then clicking OK.
  6. Start the service by right-clicking the service name in the Services console, and then clicking Start.

Set Timer job status Online in Multiserver Farm:

$farm  = Get-SPFarm
$disabledTimers = $farm.TimerService.Instances | where {$_.Status -ne "Online"}
if ($disabledTimers -ne $null)
{
    foreach ($timer in $disabledTimers)
    {
        Write-Host "Timer service instance on server " $timer.Server.Name " is not Online. Current status:" $timer.Status
        Write-Host "Attempting to set the status of the service instance to online"
        $timer.Status = [Microsoft.SharePoint.Administration.SPObjectStatus]::Online
        $timer.Update()
    }
}
else
{
    Write-Host "All Timer Service Instances in the farm are online! No problems found"

}


Timer job restart in Multiserver farm:

Use powershell script to restart timer services of all servers in a farm. Run below script in any server of a farm.

$farm = Get-SPFarm

$farm.TimerService.Instances | foreach {$_.Stop();$_.Start();}



You can get this job done in more interactive way by running below bunch of lines in SharePoint Management Shell


[array]$servers= Get-SPServer | ? {$_.Role -eq "Application"}
foreach ($server in $servers)
{
    Write-Host "Restarting Timer Service on $server"
    $Service = Get-WmiObject -Computer $server.name Win32_Service -Filter "Name='SPTimerV4'"
    if ($Service -ne $null)
    {
        $Service.InvokeMethod('StopService',$null)
        Start-Sleep -s 8
        $service.InvokeMethod('StartService',$null)
        Start-Sleep -s 5
        Write-Host -ForegroundColor Green "Timer Job successfully restarted on $server"
    }
    else
    { 
        Write-Host -ForegroundColor Red "Could not find SharePoint Timer Service on $server"
    }
}