How to Restart and Manage TeamViewer Services Using PowerShell

In IT management, ensuring the continuity and functionality of essential services is crucial. TeamViewer, a popular remote support tool, often needs to be operational at all times. However, services can occasionally be disrupted, requiring swift action to restore them. This blog post delves into a PowerShell script designed to restart and manage the TeamViewer service efficiently, ensuring minimal downtime and maximum productivity.

Background

PowerShell scripts are invaluable tools for IT professionals and Managed Service Providers (MSPs). They automate routine tasks, enforce consistency, and reduce the potential for human error. The script we’re discussing today focuses on the TeamViewer service.

Given its role in remote support, any downtime can significantly impact service delivery. This script not only restarts the TeamViewer service but also includes mechanisms to re-enable it if it has been disabled, making it a versatile tool in an IT professional’s arsenal.

The Script:

#Requires -Version 5.1

<#
.SYNOPSIS
    Restarts the TeamViewer Service. Use "Set to Automatic" if the service was disabled.
.DESCRIPTION
    Restarts the TeamViewer Service. Use "Set to Automatic" if the service was disabled.
.EXAMPLE
    (No Parameters)
    
    Status   Name               DisplayName                           
    ------   ----               -----------                           
    Running  TeamViewer         TeamViewer                            
    Attempt 1 has completed!
    TeamViewer has restarted successfully!

PARAMETER: -Enable
    Re-Enables disabled TeamViewer services.

PARAMETER: -Attempts "7" 
    Overrides the number of attempts the script will make to restart the service. Simply replace 7 with your desired number of attempts.

PARAMETER: -WaitTimeInSecs "30"
    Overrides the amount of time in between attempts. Defaults to 15.

.NOTES
    Minimum OS Architecture Supported: Windows 10, Server 2016
    Release Notes: Initial release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param (
    [Parameter()]    
    [Switch]$Enable = [System.Convert]::ToBoolean($env:setToAutomatic),
    [Parameter()]
    [int]$Attempts = 3,
    [Parameter()]
    [int]$WaitTimeInSecs = 15
)

begin {
    if ($env:attempts -and $env:attempts -notlike "null") { $Attempts = $env:attempts }
    if ($env:waitTimeInSeconds -and $env:waitTimeInSeconds -notlike "null") { $WaitTimeInSecs = $env:waitTimeInSeconds }

    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    # Grabs initial set of services to try once.
    $ServiceList = Get-CimInstance -ClassName "win32_service"

    # Attempts to find the TeamViewer service using its executable name.
    function Find-Service {
        [CmdletBinding()]
        param(
            [Parameter(ValueFromPipeline)]
            [String]$Name
        )
        process {
            $ServiceList | Where-Object { $_.PathName -Like "*$Name.exe*" } 
        }
    }

    # Tests if the service was successful
    function Test-Service {
        [CmdletBinding()]
        param(
            [Parameter(ValueFromPipeline)]
            [String]$Name
        )
        process {
            $Running = Get-Service $Name | Where-Object { $_.Status -eq $Running }
            if ($Running) {
                return $True
            }
            else {
                return $False
            }
        }
    }

    # Name of each TeamViewer exe.
    $ProcessName = "TeamViewer", "TeamViewer_Service", "tv_w32", "tv_x64"
}
process {
    if (-not (Test-IsElevated)) {
        Write-Host "[Error] Access Denied. Please run with Administrator privileges."
        exit 1
    }

    # List of services to try
    $Services = $ProcessName | Find-Service

    # If no TeamViewer service is found
    if (-not $Services) {
        Write-Host "[Error] TeamViewer appears to be missing its service. You will need to reinstall it."
        exit 1
    }

    # Loops through each service and attempts to start them
    foreach ($Service in $Services) {
        $Failed = $True
        $Attempt = 1
        While ($Attempt -le $Attempts -and $Failed -eq $True) {

            # If the service was disabled, check if -Enable was specified.
            if ($Service.StartMode -ne "Auto" -and $Enable) {
                # If so re-enable it.
                $Service | Get-Service | Set-Service -StartupType "Automatic"
            }
            elseif ($Service.StartMode -ne "Auto") {
                Write-Host "[Error] The service is not set to start automatically. Use 'Set To Automatic' to change the startup type to automatic."
                if($Service.StartMode -eq "Disabled"){ exit 1 }
            }

            # All possible service states
            Switch ($Service.State) {
                "Running" { $Service | Get-Service | Restart-Service -PassThru }
                "Paused" { $Service | Get-Service | Resume-Service -PassThru }
                "Pending" {
                    $Service | Get-Service | Stop-Service
                    Start-Sleep -Seconds 2  # Ensure the service has time to stop
                    $Service | Get-Service | Start-Service -PassThru
                }
                "Stopped" { $Service | Get-Service | Start-Service -PassThru }
            }

            Start-Sleep -Seconds $WaitTimeInSecs

            # Feedback on the number of attempts made. Multiple attempts may indicate that TeamViewer needs to be reinstalled.
            Write-Host "Attempt $Attempt completed."

            $Attempt++
            $Failed = $Service.Name | Test-Service
        }
    }
    $Failed = $Services | Get-Service | Where-Object { $_.Status -ne "Running" }

    if ($Failed) {
        Write-Host "[Error] Unable to start the service!"
        exit 1
    }
    else {
        Write-Host "TeamViewer has restarted successfully!"
        exit 0
    }
}
end {
    
    
    
}

 

Access over 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

The script’s primary function is to restart the TeamViewer service, with added functionalities to set the service to start automatically if it’s disabled and to customize the number of restart attempts and waiting periods between attempts.

Key Components

 1. Parameters and Initialization

The script starts by defining parameters: $Enable, $Attempts, and $WaitTimeInSecs. These parameters allow customization, making the script adaptable to different scenarios.

2. Elevation Check

The script includes a function to check if it is running with administrator privileges, which is necessary for service management tasks.

3. Service Discovery

It retrieves a list of all services and filters them to find those related to TeamViewer.

4. Service Status Check

Another function verifies if the specified service is running.

5. Service Management Loop

The loop attempts to restart the TeamViewer service up to the specified number of attempts, pausing between attempts as defined.

Potential Use Cases

Consider an IT support scenario where TeamViewer services on a remote machine stop unexpectedly. An IT professional can use this script to restart the service remotely, ensuring minimal disruption to support operations. For instance, during a critical support session, if the service stops, the script can be executed to bring it back online without needing manual intervention.

Comparisons

This script offers a streamlined approach compared to manual restarts or using other tools like Windows Services Manager. While the latter requires manual checks and restarts, this script automates the process, ensuring consistent and quick resolutions.

FAQs

Q: What happens if the service is disabled?

A: The script can re-enable the service if the -Enable parameter is used.

Q: Can I adjust the number of restart attempts?

A: Yes, use the -Attempts parameter to specify the desired number of attempts.

Q: What if the script is not run with administrator privileges?

A: The script checks for elevation and will exit with an error message if not run as an administrator.

Implications

Automating the restart of critical services like TeamViewer reduces downtime and improves response times. However, it’s essential to ensure that scripts like these are used responsibly and with proper permissions, as they have the potential to disrupt services if misconfigured.

Recommendations

  • Test in a Controlled Environment: Before deploying in a live environment, test the script in a controlled setup to ensure it behaves as expected.
  • Monitor Service Health: Use monitoring tools to track the health of TeamViewer services and trigger the script automatically if issues are detected.
  • Keep the Script Updated: Ensure the script is updated to accommodate any changes in service names or executable paths.

Final Thoughts

Using scripts to manage services is a powerful technique for IT professionals. This particular script for restarting TeamViewer services showcases how automation can enhance efficiency and reliability. For IT management solutions, NinjaOne provides a robust platform that can integrate such scripts, offering a comprehensive toolset for managing remote support and IT operations effectively.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).