Skip to content

Stop-ServiceRemote

Windows: Stops a running system service

#Requires -Version 5.1

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

    [string]$DisplayName,

    [string]$ComputerName = $env:COMPUTERNAME,

    [switch]$Force,

    [pscredential]$Credential
)

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

        if (-not [string]::IsNullOrWhiteSpace($Name)) {
            $serviceParams.Add('Name', $Name)
        }
        elseif (-not [string]::IsNullOrWhiteSpace($DisplayName)) {
            $serviceParams.Add('DisplayName', $DisplayName)
        }
        else {
            throw "Either Name or DisplayName must be specified."
        }

        if ($ComputerName -ne $env:COMPUTERNAME) {
            $invokeParams = @{
                'ComputerName' = $ComputerName
                'ScriptBlock'  = {
                    Param($Params, $ForceStop)
                    $srv = Get-Service @Params
                    Stop-Service -InputObject $srv -Force:$ForceStop
                    $srv | Select-Object Name, DisplayName, Status
                }
                'ArgumentList' = @($serviceParams, $Force)
                'ErrorAction'  = 'Stop'
            }
            if ($null -ne $Credential) {
                $invokeParams.Add('Credential', $Credential)
            }

            $result = Invoke-Command @invokeParams
        }
        else {
            $srv = Get-Service @serviceParams
            Stop-Service -InputObject $srv -Force:$Force
            $result = $srv | Select-Object Name, DisplayName, Status
        }

        $output = [PSCustomObject]@{
            Name         = $result.Name
            Status       = $result.Status
            ComputerName = $ComputerName
            Action       = "Stopped"
            Timestamp    = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        }

        Write-Output $output
    }
    catch {
        throw
    }
}

Specifies the internal name of the service to stop.

Specifies the display name of the service to stop.

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

Off

If set, stops the service even if it has dependent services.

Specifies a PSCredential object for remote connection.

An interactive directory of PowerShell scripts.