{"id":807216,"date":"2026-05-12T09:21:33","date_gmt":"2026-05-12T09:21:33","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=807216"},"modified":"2026-05-12T09:21:33","modified_gmt":"2026-05-12T09:21:33","slug":"como-reiniciar-um-servico-com-o-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/pt-br\/script-hub\/como-reiniciar-um-servico-com-o-powershell\/","title":{"rendered":"Como reiniciar um servi\u00e7o com o PowerShell: Um guia passo a passo"},"content":{"rendered":"<p>Como profissionais de TI e <a href=\"https:\/\/www.ninjaone.com\/what-is-an-msp\/\">provedores de servi\u00e7os gerenciados (MSPs)<\/a>, a tarefa de gerenciar e otimizar os servi\u00e7os do sistema \u00e9 parte integrante de nossas fun\u00e7\u00f5es. O PowerShell, uma linguagem de script robusta, oferece uma maneira eficiente de executar essas tarefas. Ele permite a automa\u00e7\u00e3o de tarefas, simplifica opera\u00e7\u00f5es complexas com apenas algumas linhas de c\u00f3digo e facilita o gerenciamento de servi\u00e7os em v\u00e1rias m\u00e1quinas simultaneamente.<\/p>\n<h2>O roteiro<\/h2>\n<p><div class=\"button-wrap orange-button \"><a href=\"#\" data-js=\"button-script-cta\" class=\"button script-cta\" data-js=\"script-cta\"  data-modal=\"200228\" >Email me the script<\/a><\/div><br \/>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">&lt;#\r\n.SYNOPSIS\r\n    Restart one or more services.\r\n.DESCRIPTION\r\n    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.\r\n.EXAMPLE\r\n     -Name \"ServiceName\"\r\n    Restarts a service with the name ServiceName\r\n.EXAMPLE\r\n     -Name \"ServiceName\",\"AnotherServiceName\" -WaitTimeInSecs 15\r\n    Restarts two services with the names ServiceName and AnotherServiceName and waits 15 Seconds for them all to start\r\n.EXAMPLE\r\n    PS C:&gt; Restart-Service.ps1 -Name \"ServiceName\"\r\n    Restarts a service with the name ServiceName\r\n.EXAMPLE\r\n    PS C:&gt; Restart-Service.ps1 -Name \"ServiceName\",\"AnotherServiceName\" -WaitTimeInSecs 15\r\n    Restarts two services with the names ServiceName and AnotherServiceName and waits 15 Seconds for them all to start\r\n.NOTES\r\n    Exit Code 0: All service(s) restarted\r\n    Exit Code 1: Some or all service(s) failed to restart\r\n    Release Notes:\r\n    Initial Release\r\nBy 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.\r\n    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. \r\n    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. \r\n    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. \r\n    Warranty Disclaimer: The script is provided \u201cas is\u201d and \u201cas available\u201d, 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. \r\n    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. \r\n    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. \r\n    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).\r\n#&gt;\r\n[CmdletBinding()]\r\nparam (\r\n    # Name of service(s), either Name or DisplayName from Get-Service cmdlet\r\n    [Parameter(Mandatory = $true)]\r\n    [String[]]\r\n    $Name,\r\n    # The number of attempts to restart the service before giving up\r\n    [Parameter()]\r\n    [int]\r\n    $Attempts = 3,\r\n    # Duration in Seconds to wait for service(s) to start between each attempt\r\n    [Parameter()]\r\n    [int]\r\n    $WaitTimeInSecs = 15\r\n)\r\n\r\nbegin {\r\n    function Test-Service {\r\n        [CmdletBinding()]\r\n        param (\r\n            [Parameter()]\r\n            [String[]]\r\n            $Services\r\n        )\r\n        if ((Get-Service | Where-Object { ($_.Name -in $Services -or $_.DisplayName -in $Services) -and $_.Status -like \"Running\" }).Count -gt 0) {\r\n            $true\r\n        }\r\n        else {\r\n            $false\r\n        }\r\n    }\r\n    $FailedToStart = 0\r\n}\r\nprocess {\r\n    # Get service(s)\r\n    $Services = Get-Service | Where-Object { $_.Name -in $Name -or $_.DisplayName -in $Name }\r\n    if ($Services.Count -eq 0) {\r\n        Write-Error \"No service(s) found.\"\r\n        exit 1\r\n    }\r\n\r\n    # Restart service(s)\r\n    $Services | ForEach-Object {\r\n        $AttemptCounter = $Attempts\r\n        # Restart the service\r\n        $Service = $_ | Restart-Service -PassThru\r\n        # Wait till status of service reaches Running, timeout after $WaitTimeInSecs seconds\r\n        $Service.WaitForStatus([System.ServiceProcess.ServiceControllerStatus]::Running, [timespan]::FromSeconds($WaitTimeInSecs)) | Out-Null\r\n        # Loop till either the service is in a running state or our $AttemptCounter reaches 0 or less\r\n        while ($(Get-Service -Name $Service.ServiceName).Status -ne [System.ServiceProcess.ServiceControllerStatus]::Running -or $AttemptCounter -le 0) {\r\n            # Start service\r\n            Start-Service -Name $Service.ServiceName\r\n            # Wait $WaitTimeInSecs seconds\r\n            Start-Sleep -Seconds $WaitTimeInSecs\r\n            $AttemptCounter = $AttemptCounter - 1\r\n        }\r\n        if ($((Get-Service -Name $Service.ServiceName).Status -ne [System.ServiceProcess.ServiceControllerStatus]::Running)) {\r\n            # Add 1 to later show the count of services that failed to reach the running state\r\n            $FailedToStart = $FailedToStart + 1\r\n            Write-Error -Message \"Failed to start service( $($Service.ServiceName) ) after $Attempts attempts.\"\r\n        }\r\n    }\r\n\r\n    # Print out services with their status\r\n    Get-Service | Where-Object { $_.Name -in $Name -or $_.DisplayName -in $Name }\r\n\r\n    # Check if service(s) have started\r\n    if ($FailedToStart -eq 0) {\r\n        # All service(s) have been restarted\r\n        Write-Host \"All Service(s) restarted.\"\r\n        exit 0\r\n    }\r\n    else {\r\n        # Some or all Service(s) failed to restart\r\n        Write-Error -Message \"Failed to start $FailedToStart service(s).\"\r\n        exit 1\r\n    }\r\n}\r\nend {}<\/pre>\n<p>&nbsp;<\/p>\n<div class=\"button-wrap orange-button \"><a href=\"https:\/\/www.ninjaone.com\/get-started\/deploy-with-ninjaone\/\" data-js=\"button-script-deploy-cta\" class=\"button script-deploy-cta\">Deploy with NinjaOne<\/a><\/div><div class=\"in-context-cta\"><p>Acesse mais de 300 scripts no NinjaOne Dojo<\/p>\n<p><a href=\"https:\/\/www.ninjaone.com\/freetrialform\/\">Obter acesso<\/a><\/p>\n<\/div><\/p>\n<h2>Explorando o Cmdlet Restart-Service<\/h2>\n<p>O cmdlet `Restart-Service` do PowerShell \u00e9 uma ferramenta avan\u00e7ada que permite reiniciar um servi\u00e7o em um computador local ou remoto. Esse comando consolida os processos de interrup\u00e7\u00e3o e inicializa\u00e7\u00e3o de um servi\u00e7o, simplificando o gerenciamento de servi\u00e7os.<\/p>\n<h2>Amplia\u00e7\u00e3o do uso de nosso script Restart-Service<\/h2>\n<p>Nosso script do PowerShell, projetado para aproveitar o cmdlet `Restart-Service`, oferece uma solu\u00e7\u00e3o abrangente para reiniciar um ou mais servi\u00e7os. Esse script, al\u00e9m de reiniciar um servi\u00e7o, tamb\u00e9m faz tr\u00eas tentativas de iniciar um servi\u00e7o se ele n\u00e3o for inicializado imediatamente, incorporando uma pausa de 15 segundos entre cada tentativa<\/p>\n<h2>Aplica\u00e7\u00f5es do script<\/h2>\n<p>Nosso script Restart-Service n\u00e3o \u00e9 apenas \u00fatil para reinicializa\u00e7\u00f5es imediatas de servi\u00e7os, mas tamb\u00e9m pode ser usado em v\u00e1rios cen\u00e1rios, como:<\/p>\n<h3>Reinicializa\u00e7\u00f5es programadas<\/h3>\n<p>Voc\u00ea pode usar o Agendador de tarefas em conjunto com o nosso script para reiniciar os servi\u00e7os em uma programa\u00e7\u00e3o. Isso pode ser ben\u00e9fico para servi\u00e7os que precisam de reinicializa\u00e7\u00f5es peri\u00f3dicas para liberar recursos ou manter o desempenho ideal.<\/p>\n<h3>Reinicializa\u00e7\u00f5es p\u00f3s-atualiza\u00e7\u00e3o<\/h3>\n<p>Ap\u00f3s uma atualiza\u00e7\u00e3o do sistema, alguns servi\u00e7os podem precisar ser reiniciados. Nosso script pode ser usado em um script p\u00f3s-atualiza\u00e7\u00e3o para garantir que todos os servi\u00e7os necess\u00e1rios sejam reiniciados e executados corretamente.<\/p>\n<h2>Solu\u00e7\u00e3o de problemas do script<\/h2>\n<p>Apesar da robustez dos scripts do PowerShell, pode haver casos em que as coisas n\u00e3o saiam como planejado. Aqui est\u00e3o algumas maneiras de solucionar problemas com nosso script Restart-Service:<\/p>\n<p><strong>Registros de erros<\/strong><br \/>\nO PowerShell fornece registros de erros detalhados que podem ser usados para solucionar problemas. Se o nosso script n\u00e3o conseguir reiniciar um servi\u00e7o, verifique se h\u00e1 mensagens de erro ou exce\u00e7\u00f5es nos registros de erros que possam fornecer informa\u00e7\u00f5es sobre o que deu errado.<\/p>\n<p><strong>Depura\u00e7\u00e3o do script<\/strong><br \/>\nO PowerShell oferece recursos de depura\u00e7\u00e3o que podem ser usados para percorrer o script e identificar onde o problema est\u00e1 ocorrendo. Use o comando `Set-PSDebug -Trace 1` para ativar o rastreamento do script e, em seguida, execute o script para ver uma exibi\u00e7\u00e3o linha por linha dos comandos que est\u00e3o sendo executados.<\/p>\n<h2>Considera\u00e7\u00f5es finais<\/h2>\n<p>Em conclus\u00e3o, o PowerShell oferece uma plataforma din\u00e2mica e eficiente para o gerenciamento de servi\u00e7os em sistemas Windows. Com o nosso script do PowerShell, voc\u00ea pode automatizar a reinicializa\u00e7\u00e3o de servi\u00e7os, executar opera\u00e7\u00f5es complexas com o m\u00ednimo de c\u00f3digo e gerenciar servi\u00e7os em v\u00e1rios sistemas. Fique atento a mais insights sobre como aproveitar o PowerShell para opera\u00e7\u00f5es de TI eficientes.<\/p>\n<p>Com a abrangente <a href=\"https:\/\/www.ninjaone.com\/pt-br\/\">plataforma de gerenciamento de opera\u00e7\u00f5es de TI<\/a> da NinjaOne, voc\u00ea pode integrar e dimensionar o uso de scripts personalizados, como nosso script de reinicializa\u00e7\u00e3o de servi\u00e7o do PowerShell, em v\u00e1rios pontos de extremidade. A capacidade da plataforma de implementar e gerenciar scripts de forma centralizada facilita a execu\u00e7\u00e3o de tarefas complexas em v\u00e1rios dispositivos. Isso significa que voc\u00ea pode usar nosso script para gerenciar servi\u00e7os em toda a sua rede, a partir de um \u00fanico painel, <a href=\"https:\/\/www.ninjaone.com\/pt-br\/eficiencia\/\">aumentando a efici\u00eancia<\/a> e garantindo a consist\u00eancia das suas opera\u00e7\u00f5es de TI.<\/p>\n","protected":false},"author":35,"featured_media":141588,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_acf_changed":false,"_relevanssi_hide_post":"","_relevanssi_hide_content":"","_relevanssi_pin_for_all":"","_relevanssi_pin_keywords":"","_relevanssi_unpin_keywords":"","_relevanssi_related_keywords":"","_relevanssi_related_include_ids":"","_relevanssi_related_exclude_ids":"","_relevanssi_related_no_append":"","_relevanssi_related_not_related":"","_relevanssi_related_posts":"","_relevanssi_noindex_reason":"","_lmt_disableupdate":"no","_lmt_disable":""},"operating_system":[4212],"use_cases":[12456],"class_list":["post-807216","script_hub","type-script_hub","status-publish","has-post-thumbnail","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/script_hub\/807216","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/comments?post=807216"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media\/141588"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media?parent=807216"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/operating_system?post=807216"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/use_cases?post=807216"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}