Ver demo×
×

¡Vean a NinjaOne en acción!

Al enviar este formulario, acepto la política de privacidad de NinjaOne.

Cómo reiniciar un servicio con PowerShell: guía paso a paso

Como profesionales de TI y proveedores de servicios gestionados (MSP), la tarea de gestionar y optimizar los servicios de sistemas forma parte integrante de nuestras funciones. PowerShell, un robusto lenguaje de scripting, proporciona una forma eficiente de realizar estas tareas. Permite automatizar tareas, simplificar operaciones complejas con unas pocas líneas de código y facilita la gestión de servicios en varias máquinas simultáneamente. 

El script

<#
.SYNOPSIS
    Restart one or more services.
.DESCRIPTION
    Restart one or more services. This also try three more times to get the service(s) to start, all the while waiting 15 seconds between each attempt.
.EXAMPLE
     -Name "ServiceName"
    Restarts a service with the name ServiceName
.EXAMPLE
     -Name "ServiceName","AnotherServiceName" -WaitTimeInSecs 15
    Restarts two services with the names ServiceName and AnotherServiceName and waits 15 Seconds for them all to start
.EXAMPLE
    PS C:> Restart-Service.ps1 -Name "ServiceName"
    Restarts a service with the name ServiceName
.EXAMPLE
    PS C:> Restart-Service.ps1 -Name "ServiceName","AnotherServiceName" -WaitTimeInSecs 15
    Restarts two services with the names ServiceName and AnotherServiceName and waits 15 Seconds for them all to start
.NOTES
    Exit Code 0: All service(s) restarted
    Exit Code 1: Some or all service(s) failed to restart
    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 (
    # Name of service(s), either Name or DisplayName from Get-Service cmdlet
    [Parameter(Mandatory = $true)]
    [String[]]
    $Name,
    # The number of attempts to restart the service before giving up
    [Parameter()]
    [int]
    $Attempts = 3,
    # Duration in Seconds to wait for service(s) to start between each attempt
    [Parameter()]
    [int]
    $WaitTimeInSecs = 15
)

begin {
    function Test-Service {
        [CmdletBinding()]
        param (
            [Parameter()]
            [String[]]
            $Services
        )
        if ((Get-Service | Where-Object { ($_.Name -in $Services -or $_.DisplayName -in $Services) -and $_.Status -like "Running" }).Count -gt 0) {
            $true
        }
        else {
            $false
        }
    }
    $FailedToStart = 0
}
process {
    # Get service(s)
    $Services = Get-Service | Where-Object { $_.Name -in $Name -or $_.DisplayName -in $Name }
    if ($Services.Count -eq 0) {
        Write-Error "No service(s) found."
        exit 1
    }

    # Restart service(s)
    $Services | ForEach-Object {
        $AttemptCounter = $Attempts
        # Restart the service
        $Service = $_ | Restart-Service -PassThru
        # Wait till status of service reaches Running, timeout after $WaitTimeInSecs seconds
        $Service.WaitForStatus([System.ServiceProcess.ServiceControllerStatus]::Running, [timespan]::FromSeconds($WaitTimeInSecs)) | Out-Null
        # Loop till either the service is in a running state or our $AttemptCounter reaches 0 or less
        while ($(Get-Service -Name $Service.ServiceName).Status -ne [System.ServiceProcess.ServiceControllerStatus]::Running -or $AttemptCounter -le 0) {
            # Start service
            Start-Service -Name $Service.ServiceName
            # Wait $WaitTimeInSecs seconds
            Start-Sleep -Seconds $WaitTimeInSecs
            $AttemptCounter = $AttemptCounter - 1
        }
        if ($((Get-Service -Name $Service.ServiceName).Status -ne [System.ServiceProcess.ServiceControllerStatus]::Running)) {
            # Add 1 to later show the count of services that failed to reach the running state
            $FailedToStart = $FailedToStart + 1
            Write-Error -Message "Failed to start service( $($Service.ServiceName) ) after $Attempts attempts."
        }
    }

    # Print out services with their status
    Get-Service | Where-Object { $_.Name -in $Name -or $_.DisplayName -in $Name }

    # Check if service(s) have started
    if ($FailedToStart -eq 0) {
        # All service(s) have been restarted
        Write-Host "All Service(s) restarted."
        exit 0
    }
    else {
        # Some or all Service(s) failed to restart
        Write-Error -Message "Failed to start $FailedToStart service(s)."
        exit 1
    }
}
end {}

 


Accede a más de 700 scripts en el Dojo de NinjaOne | Accede aquí

Explorar el cmdlet «Restart-Service»

El cmdlet «Restart-Service» de PowerShell es una potente herramienta que permite reiniciar un servicio en un equipo local o remoto. Este comando consolida los procesos de parada e inicio de un servicio, simplificando la gestión del mismo.

Ampliar el uso del script «Restart-Service»

Este script PowerShell, diseñado para aprovechar el cmdlet «Restart-Service», ofrece una solución completa para reiniciar uno o varios servicios. Este script, además de reiniciar un servicio, también realiza tres intentos de iniciar un servicio si no se inicializa inmediatamente, incorporando una pausa de 15 segundos entre cada intento

Aplicaciones del script

El script «Restart-Service» no sólo es útil para reiniciar servicios de forma inmediata, sino que también se puede utilizar en varios escenarios, como por ejemplo:

Reinicios programados

Puedes utilizar el Programador de Tareas junto con el script para reiniciar los servicios de forma programada.Esto puede ser beneficioso para los servicios que necesitan reinicios periódicos para liberar recursos o mantener un rendimiento óptimo.

Reinicios posteriores a la actualización

Tras una actualización del sistema, puede que sea necesario reiniciar algunos servicios. Nuestro script puede utilizarse en un script posterior a la actualización para garantizar que todos los servicios necesarios se reinicien y funcionen correctamente.

Solución de problemas con el script

A pesar de la solidez de los scripts de PowerShell, puede haber casos en los que las cosas no salgan según lo planeado. Estas son algunas formas de solucionar problemas con nuestro script «Restart-Service»:

Registros de errores

PowerShell proporciona registros de errores detallados que pueden utilizarse para solucionar problemas. Si nuestro script no consigue reiniciar un servicio, comprueba los registros de errores en busca de mensajes de error o excepciones que puedan proporcionar información sobre lo que ha fallado.

Depurar el script

PowerShell proporciona funciones de depuración que pueden utilizarse para recorrer el script e identificar dónde se produce el problema. Utiliza el comando`Set-PSDebug-Trace 1` para activar el seguimiento del script y, a continuación, ejecuta el script para una visualización línea por línea de los comandos que se están ejecutando.

Reflexiones finales

En conclusión, PowerShell proporciona una plataforma dinámica y eficaz para gestionar servicios en sistemas Windows. Con nuestro script PowerShell, puedes automatizar el reinicio de servicios, realizar operaciones complejas con un código mínimo y gestionar servicios en varios sistemas. Síguenos para más información sobre cómo aprovechar PowerShell para operaciones de TI eficientes. 

Con la plataforma integral de gestión de operaciones de TI de NinjaOne, puedes integrar y escalar el uso de scripts personalizados como nuestro script de reinicio de servicio PowerShell a través de numerosos endpoints.

La capacidad de la plataforma para desplegar y gestionar scripts de forma centralizada hace que la ejecución de tareas complejas en múltiples dispositivos sea fluida. Esto significa que puedes utilizar nuestro script para gestionar servicios en toda tu red, desde un único panel de control, mejorando la eficiencia y garantizando la coherencia en tus operaciones de TI.

Próximos pasos

La creación de un equipo de TI próspero y eficaz requiere contar con una solución centralizada que se convierta en tu principal herramienta de prestación de servicios. NinjaOne permite a los equipos de TI supervisar, gestionar, proteger y dar soporte a todos sus dispositivos, estén donde estén, sin necesidad de complejas infraestructuras locales.

Obtén más información sobre NinjaOne Endpoint Management, echa un vistazo a un tour en vivo o comienza tu prueba gratuita de la plataforma NinjaOne.

Quizá también te interese…

Términos y condiciones de NinjaOne

Al hacer clic en el botón «Acepto» que aparece a continuación, estás aceptando los siguientes términos legales, así como nuestras Condiciones de uso:

  • Derechos de propiedad: NinjaOne posee y seguirá poseyendo todos los derechos, títulos e intereses sobre el script (incluidos los derechos de autor). NinjaOne concede al usuario una licencia limitada para utilizar el script de acuerdo con estos términos legales.
  • Limitación de uso: sólo podrás utilizar el script para tus legítimos fines personales o comerciales internos, y no podrás compartirlo con terceros.
  • Prohibición de republicación: Bajo ninguna circunstancia está permitido volver a publicar el script en ninguna biblioteca de scripts que pertenezca o esté bajo el control de cualquier otro proveedor de software.
  • Exclusión de garantía: El script se proporciona «»tal cual» y «según disponibilidad», sin garantía de ningún tipo. NinjaOne no promete ni garantiza que el script esté libre de defectos o que satisfaga las necesidades o expectativas específicas del usuario.
  • Asunción de riesgos: El uso que el usuario haga del script corre por su cuenta y riesgo. El usuario reconoce que existen ciertos riesgos inherentes al uso del script, y entiende y asume cada uno de esos riesgos.
  • Renuncia y exención: El usuario no hará responsable a NinjaOne de cualquier consecuencia adversa o no deseada que resulte de su uso del script y renuncia a cualquier derecho o recurso legal o equitativo que pueda tener contra NinjaOne en relación con su uso del script.
  • CLUF: Si el usuario es cliente de NinjaOne, su uso del script está sujeto al Contrato de Licencia para el Usuario Final (CLUF).