Bekijk een demo×
×

Zie NinjaOne in actie!

Door dit formulier in te dienen geef ik aan akkoord te gaan met het privacybeleid van NinjaOne.

Hoe een Service Herstarten met PowerShell: Een Stap-voor-Stap Handleiding

Als IT-professionals en Managed Service Providers (MSP’s) is het beheren en optimaliseren van systeemservices een integraal onderdeel van onze rollen. PowerShell, een robuuste scripttaal, biedt een efficiënte manier om deze taken uit te voeren. Het maakt taakautomatisering mogelijk, vereenvoudigt complexe bewerkingen met slechts een paar regels code en vergemakkelijkt het beheer van services op meerdere machines tegelijk. 

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

 


Toegang tot meer dan 700 scripts in de NinjaOne Dojo

Toegang krijgen

Het Restart-Service Cmdlet verkennen

Het cmdlet `Restart-Service` in PowerShell is een krachtig hulpmiddel waarmee je een service op een lokale of externe computer opnieuw kunt starten. Dit commando consolideert de processen van het stoppen en starten van een service, wat het servicebeheer vereenvoudigt.

Het gebruik van ons Restart-Service Script uitbreiden

Ons PowerShell-script, ontworpen om gebruik te maken van het cmdlet `Restart-Service`, biedt een uitgebreide oplossing voor het opnieuw opstarten van een of meer services. Dit script herstart niet alleen een service, maar doet ook drie pogingen om een service te starten als deze niet meteen initialiseert, met een pauze van 15 seconden tussen elke poging

Toepassingen van het Script

Ons Restart-Service-script is niet alleen handig voor het direct herstarten van services, maar kan ook worden gebruikt in verschillende scenario’s, zoals:

Geplande Restarts

Je kunt Task Scheduler gebruiken in combinatie met ons script om services opnieuw te starten volgens een schema.Dit kan voordelig zijn voor diensten die periodiek opnieuw opgestart moeten worden om bronnen vrij te maken of om optimale prestaties te behouden.

Opnieuw opstarten na een update

Na een systeemupdate moeten sommige services mogelijk opnieuw worden opgestart. Ons script kan worden gebruikt in een post-update script om ervoor te zorgen dat alle benodigde services opnieuw worden gestart en correct draaien.

Problemen met het script oplossen

Ondanks de robuustheid van PowerShell scripts kan het voorkomen dat dingen niet gaan zoals gepland. Hier zijn enkele manieren om problemen met ons Restart-Service-script op te lossen:

Error Logs
PowerShell biedt gedetailleerde error logs die kunnen worden gebruikt om problemen op te lossen. Als ons script er niet in slaagt om een service te herstarten, controleer dan de error logs op foutmeldingen of uitzonderingen die inzicht kunnen geven in wat er fout ging.

Het script debuggen
PowerShell biedt debugfuncties die kunnen worden gebruikt om door het script te stappen en te identificerenwaar het probleem optreedt. Gebruik het `Set-PSDebug-Trace 1` commando om scripttracering in te schakelen en voer vervolgens het script uit om een regel-voor-regel een weergave te zien van de commando’s die worden uitgevoerd.

Slotbeschouwingen:

Kortom, PowerShell biedt een dynamisch en efficiënt platform voor het beheren van services op Windows-systemen. Met ons PowerShell-script kun je serviceherstartingen automatiseren, complexe bewerkingen uitvoeren met minimale code en services beheren op meerdere systemen. Blijf op de hoogte voor meer inzichten in het gebruik van PowerShell voor efficiënte IT-operaties. 

Met NinjaOne’s uitgebreide IT-platform voor operationeel beheer kunt u het gebruik van aangepaste scripts, zoals ons PowerShell-serviceherstartscript, integreren en schalen over meerdere eindpunten. De mogelijkheid van het platform om scripts centraal in te zetten en te beheren maakt het uitvoeren van complexe taken op meerdere apparaten naadloos. Dit betekent dat je ons script kunt gebruiken om services in je hele netwerk te beheren vanaf één dashboard, waardoor de efficiëntie toeneemt en je IT-activiteiten consistenter worden.

Volgende stappen

Het opbouwen van een efficiënt en effectief IT-team vereist een gecentraliseerde oplossing die fungeert als uw kerndienstleveringstool. NinjaOne stelt IT-teams in staat om al hun apparaten te monitoren, beheren, beveiligen en ondersteunen, waar ze ook zijn, zonder de noodzaak van complexe on-premises infrastructuur.

Leer meer over NinjaOne Endpoint Management, bekijk een live rondleiding, of start uw gratis trial van het NinjaOne-platform

Categorieën:

Dit vindt u misschien ook leuk

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our 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 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).