Como reiniciar um serviço com o PowerShell: Um guia passo a passo

Como profissionais de TI e provedores de serviços gerenciados (MSPs), a tarefa de gerenciar e otimizar os serviços do sistema é parte integrante de nossas funções. O PowerShell, uma linguagem de script robusta, oferece uma maneira eficiente de executar essas tarefas. Ele permite a automação de tarefas, simplifica operações complexas com apenas algumas linhas de código e facilita o gerenciamento de serviços em várias máquinas simultaneamente.

O roteiro


<#
.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 {}

 

Acesse mais de 300 scripts no NinjaOne Dojo

Obter acesso

Explorando o Cmdlet Restart-Service

O cmdlet `Restart-Service` do PowerShell é uma ferramenta avançada que permite reiniciar um serviço em um computador local ou remoto. Esse comando consolida os processos de interrupção e inicialização de um serviço, simplificando o gerenciamento de serviços.

Ampliação do uso de nosso script Restart-Service

Nosso script do PowerShell, projetado para aproveitar o cmdlet `Restart-Service`, oferece uma solução abrangente para reiniciar um ou mais serviços. Esse script, além de reiniciar um serviço, também faz três tentativas de iniciar um serviço se ele não for inicializado imediatamente, incorporando uma pausa de 15 segundos entre cada tentativa

Aplicações do script

Nosso script Restart-Service não é apenas útil para reinicializações imediatas de serviços, mas também pode ser usado em vários cenários, como:

Reinicializações programadas

Você pode usar o Agendador de tarefas em conjunto com o nosso script para reiniciar os serviços em uma programação. Isso pode ser benéfico para serviços que precisam de reinicializações periódicas para liberar recursos ou manter o desempenho ideal.

Reinicializações pós-atualização

Após uma atualização do sistema, alguns serviços podem precisar ser reiniciados. Nosso script pode ser usado em um script pós-atualização para garantir que todos os serviços necessários sejam reiniciados e executados corretamente.

Solução de problemas do script

Apesar da robustez dos scripts do PowerShell, pode haver casos em que as coisas não saiam como planejado. Aqui estão algumas maneiras de solucionar problemas com nosso script Restart-Service:

Registros de erros
O PowerShell fornece registros de erros detalhados que podem ser usados para solucionar problemas. Se o nosso script não conseguir reiniciar um serviço, verifique se há mensagens de erro ou exceções nos registros de erros que possam fornecer informações sobre o que deu errado.

Depuração do script
O PowerShell oferece recursos de depuração que podem ser usados para percorrer o script e identificar onde o problema está ocorrendo. Use o comando `Set-PSDebug -Trace 1` para ativar o rastreamento do script e, em seguida, execute o script para ver uma exibição linha por linha dos comandos que estão sendo executados.

Considerações finais

Em conclusão, o PowerShell oferece uma plataforma dinâmica e eficiente para o gerenciamento de serviços em sistemas Windows. Com o nosso script do PowerShell, você pode automatizar a reinicialização de serviços, executar operações complexas com o mínimo de código e gerenciar serviços em vários sistemas. Fique atento a mais insights sobre como aproveitar o PowerShell para operações de TI eficientes.

Com a abrangente plataforma de gerenciamento de operações de TI da NinjaOne, você pode integrar e dimensionar o uso de scripts personalizados, como nosso script de reinicialização de serviço do PowerShell, em vários pontos de extremidade. A capacidade da plataforma de implementar e gerenciar scripts de forma centralizada facilita a execução de tarefas complexas em vários dispositivos. Isso significa que você pode usar nosso script para gerenciar serviços em toda a sua rede, a partir de um único painel, aumentando a eficiência e garantindo a consistência das suas operações de TI.

Próximas etapas

Montar uma equipe de TI eficaz requer uma solução centralizada que seja a principal ferramenta de entrega de serviços. Com NinjaOne, a TI monitora, gerencia, protege e oferece suporte a todos os dispositivos, onde quer que estejam, dispensando infraestrutura complexa no local.

Saiba mais sobre a solução NinjaOne Remote Script Deployment, agende uma demonstração, ou inicie sua avaliação gratuita da plataforma NinjaOne.

Categories:

You might also like