Skip to content

Restart-ServiceRemote

Windows: Restarts a system service on a local or remote computer

#Requires -Version 5.1

[CmdletBinding()]
Param
(
    [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
    [string]$Name,

    [string]$ComputerName = $env:COMPUTERNAME,

    [switch]$Force
)

Process {
    try {
        $serviceParams = @{
            'Name'         = $Name
            'ComputerName' = $ComputerName
            'ErrorAction'  = 'Stop'
        }

        if ($Force) {
            $serviceParams.Add('Force', $true)
        }

        Write-Verbose "Attempting to restart service '$Name' on '$ComputerName'..."
        Restart-Service @serviceParams

        Start-Sleep -Seconds 2
        $status = Get-Service -Name $Name -ComputerName $ComputerName -ErrorAction Stop
            
        $result = [PSCustomObject]@{
            ServiceName  = $Name
            ComputerName = $ComputerName
            Status       = $status.Status
            Timestamp    = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        }

        Write-Output $result
    }
    catch {
        throw
    }
}

Specifies the name of the service to restart.

Specifies the name of the target computer. Defaults to the local computer.

Off

Indicates that the service should be restarted even if it has dependent services.

An interactive directory of PowerShell scripts.