Skip to content

Start-ServiceRemote

Windows: Starts a stopped system service

#Requires -Version 5.1

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

    [string]$DisplayName,

    [string]$ComputerName = $env:COMPUTERNAME,

    [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)
                    $srv = Get-Service @Params
                    Start-Service -InputObject $srv
                    $srv | Select-Object Name, DisplayName, Status
                }
                'ArgumentList' = $serviceParams
                'ErrorAction'  = 'Stop'
            }
            if ($null -ne $Credential) {
                $invokeParams.Add('Credential', $Credential)
            }

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

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

        Write-Output $output
    }
    catch {
        throw
    }
}

Specifies the internal name of the service to start.

Specifies the display name of the service to start.

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

Specifies a PSCredential object for remote connection.

An interactive directory of PowerShell scripts.