{"id":208600,"date":"2023-09-11T11:00:22","date_gmt":"2023-09-11T11:00:22","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/reiniciar-servicio-powershell\/"},"modified":"2024-03-04T16:24:15","modified_gmt":"2024-03-04T16:24:15","slug":"reiniciar-servicio-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/es\/script-hub\/reiniciar-servicio-powershell\/","title":{"rendered":"C\u00f3mo reiniciar un servicio con PowerShell: gu\u00eda paso a paso"},"content":{"rendered":"<p><span class=\"TextRun SCXW249427078 BCX0\" lang=\"EN-US\" data-contrast=\"auto\"><span class=\"NormalTextRun SCXW249427078 BCX0\">Como profesionales de TI y<\/span><\/span>\u00a0<a class=\"Hyperlink SCXW249427078 BCX0\" href=\"https:\/\/www.ninjaone.com\/es\/que-es-un-msp\" target=\"_blank\" rel=\"noreferrer noopener\"><span class=\"TextRun Underlined SCXW249427078 BCX0\" lang=\"EN-US\" data-contrast=\"none\"><span class=\"NormalTextRun SCXW249427078 BCX0\" data-ccp-charstyle=\"Hyperlink\">proveedores de servicios gestionados (MSP)<\/span><\/span><\/a><span class=\"TextRun SCXW249427078 BCX0\" lang=\"EN-US\" data-contrast=\"auto\"><span class=\"NormalTextRun SCXW249427078 BCX0\">, la tarea de gestionar y <\/span><span class=\"NormalTextRun SCXW249427078 BCX0\">optimizar <\/span><span class=\"NormalTextRun SCXW249427078 BCX0\">los servicios de sistemas forma parte integrante de nuestras <\/span><span class=\"NormalTextRun ContextualSpellingAndGrammarErrorV2Themed SCXW249427078 BCX0\">funciones<\/span><span class=\"NormalTextRun SCXW249427078 BCX0\">. PowerShell, un robusto lenguaje de scripting, <\/span><span class=\"NormalTextRun SCXW249427078 BCX0\">proporciona <\/span><span class=\"NormalTextRun SCXW249427078 BCX0\">una forma eficiente de realizar estas tareas. Permite automatizar tareas, simplificar operaciones complejas con unas pocas l\u00edneas de c\u00f3digo y <\/span><span class=\"NormalTextRun SCXW249427078 BCX0\">facilita la <\/span><span class=\"NormalTextRun SCXW249427078 BCX0\">gesti\u00f3n de servicios en varias m\u00e1quinas simult\u00e1neamente.<\/span><\/span><span class=\"EOP SCXW249427078 BCX0\" data-ccp-props=\"{}\">\u00a0<\/span><\/p>\n<h2>El script<\/h2>\n<p><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<br \/>\n<div class=\"in-context-cta\"><p>Accede a m\u00e1s de 700 scripts en el Dojo de NinjaOne | <a href=\"https:\/\/www.ninjaone.com\/es\/prueba-gratuita-formulario\/\">Accede aqu\u00ed<\/a><\/p>\n<\/div><\/p>\n<h2>Explorar el cmdlet \u00abRestart-Service\u00bb<\/h2>\n<p><span class=\"TextRun SCXW74170526 BCX0\" lang=\"EN-US\" data-contrast=\"auto\"><span class=\"NormalTextRun SCXW74170526 BCX0\">El cmdlet \u00abRestart-Service\u00bb de PowerShell es una potente herramienta que permite reiniciar un servicio en un equipo local o remoto. Este comando <\/span><span class=\"NormalTextRun SCXW74170526 BCX0\">consolida <\/span><span class=\"NormalTextRun SCXW74170526 BCX0\">los procesos de parada e inicio de un servicio, simplificando la gesti\u00f3n del mismo.<\/span><\/span><\/p>\n<h2>Ampliar el uso del script \u00abRestart-Service\u00bb<\/h2>\n<p><span class=\"TextRun SCXW67305974 BCX0\" lang=\"EN-US\" data-contrast=\"auto\"><span class=\"NormalTextRun SCXW67305974 BCX0\">Este script PowerShell, dise\u00f1ado para <\/span><span class=\"NormalTextRun SCXW67305974 BCX0\">aprovechar <\/span><span class=\"NormalTextRun SCXW67305974 BCX0\">el cmdlet \u00abRestart-Service\u00bb, <\/span><span class=\"NormalTextRun SCXW67305974 BCX0\">ofrece <\/span><span class=\"NormalTextRun SCXW67305974 BCX0\">una soluci\u00f3n completa para reiniciar uno o varios servicios. Este script, adem\u00e1s de reiniciar un servicio, tambi\u00e9n realiza tres intentos de iniciar un servicio si <\/span><span class=\"NormalTextRun SCXW67305974 BCX0\">no <\/span><span class=\"NormalTextRun SCXW67305974 BCX0\">se inicializa <\/span><span class=\"NormalTextRun SCXW67305974 BCX0\">inmediatamente<\/span><span class=\"NormalTextRun SCXW67305974 BCX0\">, incorporando una pausa de 15 segundos entre cada intento<\/span><\/span><\/p>\n<h2>Aplicaciones del script<\/h2>\n<p><span class=\"TextRun SCXW221271371 BCX0\" lang=\"EN-US\" data-contrast=\"auto\"><span class=\"NormalTextRun SCXW221271371 BCX0\">El script \u00abRestart-Service\u00bb no s\u00f3lo es \u00fatil para reiniciar servicios de forma inmediata, sino que tambi\u00e9n se puede utilizar en varios escenarios, como por ejemplo:<\/span><\/span><\/p>\n<h3>Reinicios programados<\/h3>\n<p><span class=\"TextRun SCXW175456835 BCX0\" lang=\"EN-US\" data-contrast=\"auto\"><span class=\"NormalTextRun SCXW175456835 BCX0\">Puedes utilizar el Programador de Tareas junto con el script para reiniciar los servicios de forma programada.<\/span><span class=\"NormalTextRun SCXW175456835 BCX0\">Esto puede ser beneficioso para los servicios que necesitan reinicios peri\u00f3dicos para liberar recursos o <\/span><span class=\"NormalTextRun SCXW175456835 BCX0\">mantener<\/span> <span class=\"NormalTextRun SCXW175456835 BCX0\">un rendimiento <\/span><span class=\"NormalTextRun SCXW175456835 BCX0\">\u00f3ptimo.<\/span><\/span><\/p>\n<h3>Reinicios posteriores a la actualizaci\u00f3n<\/h3>\n<p><span class=\"TextRun SCXW18560881 BCX0\" lang=\"EN-US\" data-contrast=\"auto\"><span class=\"NormalTextRun SCXW18560881 BCX0\">Tras una actualizaci\u00f3n del sistema, puede que sea necesario reiniciar algunos servicios. Nuestro script puede utilizarse en un script posterior a la actualizaci\u00f3n para garantizar que todos los servicios necesarios se reinicien y funcionen correctamente.<\/span><\/span><\/p>\n<h2>Soluci\u00f3n de problemas con el script<\/h2>\n<p>A pesar de la solidez de los scripts de PowerShell, puede haber casos en los que las cosas no salgan seg\u00fan lo planeado. Estas son algunas formas de solucionar problemas con nuestro script <span class=\"TextRun SCXW221271371 BCX0\" lang=\"EN-US\" data-contrast=\"auto\"><span class=\"NormalTextRun SCXW221271371 BCX0\">\u00abRestart-Service\u00bb<\/span><\/span>:<\/p>\n<p><strong>Registros de errores<\/strong><\/p>\n<p><span class=\"TextRun SCXW56490188 BCX0\" lang=\"EN-US\" data-contrast=\"auto\"><span class=\"NormalTextRun SCXW56490188 BCX0\">PowerShell <\/span><span class=\"NormalTextRun SCXW56490188 BCX0\">proporciona <\/span><span class=\"NormalTextRun SCXW56490188 BCX0\">registros de errores detallados que pueden utilizarse para solucionar problemas. Si nuestro script <\/span><span class=\"NormalTextRun SCXW56490188 BCX0\">no consigue <\/span><span class=\"NormalTextRun SCXW56490188 BCX0\">reiniciar un servicio, comprueba los registros de errores en busca de mensajes de error o excepciones que puedan <\/span><span class=\"NormalTextRun SCXW56490188 BCX0\">proporcionar <\/span><span class=\"NormalTextRun SCXW56490188 BCX0\">informaci\u00f3n sobre lo que ha fallado.<\/span><\/span><\/p>\n<p><strong>Depurar el script<\/strong><\/p>\n<p><span class=\"TextRun SCXW197375251 BCX0\" lang=\"EN-US\" data-contrast=\"auto\"><span class=\"NormalTextRun SCXW197375251 BCX0\">PowerShell <\/span><span class=\"NormalTextRun SCXW197375251 BCX0\">proporciona <\/span><span class=\"NormalTextRun SCXW197375251 BCX0\">funciones de depuraci\u00f3n que pueden utilizarse para recorrer el script e <\/span><span class=\"NormalTextRun SCXW197375251 BCX0\">identificar <\/span><span class=\"NormalTextRun SCXW197375251 BCX0\">d\u00f3nde se produce el problema. Utiliza el comando`Set-<\/span><span class=\"NormalTextRun SpellingErrorV2Themed SCXW197375251 BCX0\">PSDebug<\/span><span class=\"NormalTextRun SCXW197375251 BCX0\">-Trace 1` para activar el seguimiento del script y, a continuaci\u00f3n, ejecuta el script para una visualizaci\u00f3n l\u00ednea por l\u00ednea de los comandos que se est\u00e1n ejecutando.<\/span><\/span><\/p>\n<h2>Reflexiones finales<\/h2>\n<p><span data-contrast=\"auto\">En conclusi\u00f3n, PowerShell proporciona una plataforma din\u00e1mica y eficaz para gestionar servicios en sistemas Windows. Con nuestro script PowerShell, puedes automatizar el reinicio de servicios, realizar operaciones complejas con un c\u00f3digo m\u00ednimo y gestionar servicios en varios sistemas. S\u00edguenos para m\u00e1s informaci\u00f3n sobre c\u00f3mo aprovechar PowerShell para operaciones de TI eficientes.<\/span><span data-ccp-props=\"{}\">\u00a0<\/span><\/p>\n<p><span data-contrast=\"auto\">Con la plataforma <\/span><span data-contrast=\"none\">integral <a href=\"https:\/\/www.ninjaone.com\/es\/\">de gesti\u00f3n de operaciones de TI de NinjaOne<\/a><\/span><span data-contrast=\"auto\">, puedes integrar y escalar el uso de scripts personalizados como nuestro script de reinicio de servicio PowerShell a trav\u00e9s de numerosos endpoints. <\/span><\/p>\n<p><span data-contrast=\"auto\">La capacidad de la plataforma para desplegar y gestionar scripts de forma centralizada hace que la ejecuci\u00f3n de tareas complejas en m\u00faltiples dispositivos sea fluida. Esto significa que puedes utilizar nuestro script para gestionar servicios en toda tu red, desde un \u00fanico panel de control, <a href=\"https:\/\/www.ninjaone.com\/es\/eficiencia\/\">mejorando la eficiencia<\/a> y garantizando la coherencia en tus operaciones de TI.<\/span><\/p>\n","protected":false},"author":35,"featured_media":206752,"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":[4265],"class_list":["post-208600","script_hub","type-script_hub","status-publish","has-post-thumbnail","hentry","script_hub_category-windows","use_cases-configuracion-del-sistema"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub\/208600","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/comments?post=208600"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media\/206752"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media?parent=208600"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/operating_system?post=208600"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/use_cases?post=208600"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}