Guarda una demo×
×

Guarda NinjaOne in azione!

Inviando questo modulo, accetto La politica sulla privacy di NinjaOne.

Come riavviare un servizio con PowerShell: Una guida passo per passo

Come professionisti IT e fornitori di servizi gestiti (MSP) il compito di gestire e ottimizzare i servizi di sistema è parte integrante del nostro ruolo. PowerShell, un potente linguaggio di scripting, fornisce un modo efficiente per eseguire diverse attività. Per esempio, è possibile riavviare un servizio con Powershell,  e questo linguaggio consente l’automazione delle attività, semplifica operazioni complesse usando poche righe di codice e facilita la gestione dei servizi su più macchine contemporaneamente. 

Lo 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 {}

 


Accedi a oltre 700 script nel Dojo di NinjaOne Ottieni l’accesso

Panoramica sul cmdlet Restart-Service

Il cmdlet `Restart-Service` di PowerShell è un potente strumento che consente di riavviare un servizio su un computer locale o remoto. Questo comando centralizza i processi di arresto e avvio di un servizio, semplificandone la gestione.

Estendere l’uso del nostro script Restart-Service

Il nostro script PowerShell, progettato per sfruttare il cmdlet `Restart-Service`, fornisce una soluzione completa per il riavvio di uno o più servizi. Questo script, oltre a permettere di riavviare un servizio con PowerShell, effettua anche tre tentativi di avviare un servizio se questo non si inizializza immediatamente , incorporando una pausa di 15 secondi tra un tentativo e l’altro.

Applicazioni dello script

Il nostro script Restart-Service non è utile solo per riavviare un servizio con PowerShell in modo immediato, ma può essere utilizzato anche in altri scenari, come per esempio:

Riavvii programmati

Puoi utilizzare il Task Scheduler insieme al nostro script per riavviare un servizio con PowerShell secondo una pianificazione. Questo può essere vantaggioso per i servizi che hanno bisogno di riavvii periodici per liberare risorse o mantenere un livello ottimale di prestazioni.

Riavvii post-aggiornamento

Dopo un aggiornamento del sistema, potrebbe essere necessario riavviare alcuni servizi. Il nostro script per riavviare un servizio con PowerShell può essere utilizzato in uno script post-aggiornamento per garantire che tutti i servizi necessari siano riavviati e funzionino correttamente.

Risoluzione dei problemi dello script per riavviare un servizio con Powershell

Nonostante la solidità degli script PowerShell, possono verificarsi situazioni in cui le cose non vanno come previsto. Ecco alcuni modi per risolvere eventuali problemi con il nostro script Restart-Service per riavviare un servizio con PowerShell:

Log degli errori

PowerShell fornisce log dettagliati degli errori che possono essere utilizzati per la risoluzione dei problemi. Se il nostro script non riesce a riavviare un servizio, controlla i log degli errori per individuare eventuali messaggi di errore o eccezioni che possono fornire indicazioni su cosa è andato storto.

Debug dello script

PowerShell offre funzioni di debug che possono essere utilizzate per analizzare lo script e identificare dove si verifica il problema. Usa il comando `Set-PSDebug -Trace 1` per abilitare il tracciamento dello script e poi esegui lo script per vedere una visualizzazione riga per riga dei comandi eseguiti.

Considerazioni finali

In conclusione, PowerShell fornisce una piattaforma dinamica ed efficiente per la gestione dei servizi sui sistemi Windows. Con il nostro script per riavviare un servizio con PowerShell potrai automatizzare i riavvii dei servizi, eseguire operazioni complesse con un codice minimo e gestire i servizi su più sistemi. Resta sintonizzato per ulteriori approfondimenti sull’utilizzo di PowerShell per rendere le operazioni IT efficienti. 

Con NinjaOne e la sua soluzione centralizzata per la gestione delle operazioni IT, potrai integrare e scalare, anche su un grande numero di endpoint, l’uso di script personalizzati come il nostro script PowerShell per il riavvio dei servizi. La capacità della piattaforma di distribuire e gestire gli script in modo centralizzato consente di eseguire attività complesse su più dispositivi senza problemi. Ciò significa che potrai utilizzare il nostro script per gestire i servizi della tua intera rete da un’unica dashboard, migliorando l’efficienza e garantendo la coerenza delle tue operazioni IT.

Passi successivi

La creazione di un team IT efficiente ed efficace richiede una soluzione centralizzata che funga da principale strumento per la fornitura di servizi. NinjaOne consente ai team IT di monitorare, gestire, proteggere e supportare tutti i dispositivi, ovunque essi si trovino, senza la necessità di una complessa infrastruttura locale.

Per saperne di più su NinjaOne Endpoint Management, fai un tour dal vivo, o inizia la tua prova gratuita della piattaforma NinjaOne.

Ti potrebbe interessare anche

Termini e condizioni NinjaOne

Cliccando sul pulsante “Accetto” qui sotto, dichiari di accettare i seguenti termini legali e le nostre condizioni d’uso:

  • Diritti di proprietà: NinjaOne possiede e continuerà a possedere tutti i diritti, i titoli e gli interessi relativi allo script (compreso il copyright). NinjaOne ti concede una licenza limitata per l’utilizzo dello script in conformità con i presenti termini legali.
  • Limitazione d’uso: Puoi utilizzare lo script solo per legittimi scopi personali o aziendali interni e non puoi condividere lo script con altri soggetti.
  • Divieto di ripubblicazione: In nessun caso ti è consentito ripubblicare lo script in una libreria di script appartenente o sotto il controllo di un altro fornitore di software.
  • Esclusione di garanzia: Lo script viene fornito “così com’è” e “come disponibile”, senza garanzie di alcun tipo. NinjaOne non promette né garantisce che lo script sia privo di difetti o che soddisfi le tue esigenze o aspettative specifiche.
  • Assunzione del rischio: L’uso che farai dello script è da intendersi a tuo rischio. Riconosci che l’utilizzo dello script comporta alcuni rischi intrinseci, che comprendi e sei pronto ad assumerti.
  • Rinuncia e liberatoria: Non riterrai NinjaOne responsabile di eventuali conseguenze negative o indesiderate derivanti dall’uso dello script e rinuncerai a qualsiasi diritto legale o di equità e a qualsiasi rivalsa nei confronti di NinjaOne in relazione all’uso dello script.
  • EULA: Se sei un cliente NinjaOne, l’uso dello script è soggetto al Contratto di licenza con l’utente finale (EULA) applicabile.