Skip to main content

Start Windows Service If Stopped

This page documents the Start-ServiceParameterized.ps1 script, which is designed to start a Windows service if it is currently stopped. The script supports both named and positional parameters and includes basic error handling.

Overview

This PowerShell script checks the status of a specified Windows service and starts it if it is not already running. It accepts the service name either as a named parameter or as a positional argument.


Usage

You can run the script using either method below:

1. Named Parameter

 

powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Start-ServiceParameterized.ps1 -ServiceName wuauserv

2. Positional Argument

powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Start-ServiceParameterized.ps1 wuauserv

3. Example for Tanium Package (code field):

cmd.exe /d /c powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -NonInteractive -NoProfile -File .\Start-ServiceParameterized.ps1 $1

Script Behavior

The script performs these steps:

  1. Accepts the service name as either a named parameter (-ServiceName) or a positional argument.

  2. If no service name is provided, the script returns an error.

  3. Retrieves the Windows service using Get-Service.

  4. Evaluates the service status:

    • If not running, attempts to start the service.

    • If running, outputs that no action is required

Script Code:

####################################################################################################
# Start a Windows service if stopped
# Service name can be passed as:
#  - Named parameter: -ServiceName wuauserv
#  - Positional/argument: wuauserv
# code: powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Start-ServiceParameterized.ps1 $1
#####################################################################################################

param(
    [Parameter(Mandatory = $false, Position = 0)]
    [string]$ServiceName
)

# Fallback: if ServiceName wasn't bound but args were passed
if (-not $ServiceName -and $args.Count -gt 0) {
    $ServiceName = $args[0]
}

if (-not $ServiceName) {
    Write-Output "ERROR: No service name specified. Please pass a service name."
    exit 1
}

Write-Output "Checking service: $ServiceName"

try {
    $svc = Get-Service -Name $ServiceName -ErrorAction Stop

    if ($svc.Status -ne "Running") {
        Write-Output "Starting service '$ServiceName'..."
        Start-Service -Name $ServiceName -ErrorAction Stop
        Write-Output "Service '$ServiceName' successfully started."
    } else {
        Write-Output "Service '$ServiceName' is already running."
    }
}
catch {
    Write-Output "Unable to access service '$ServiceName': $_"
    exit 2
}

Notes

  • Designed for automation platforms such as Tanium, SCCM, and Intune.

  • Requires appropriate administrative privileges to start services.

 

Â