Restart Service Domain Wide

Purpose: Sometimes you need to restart a service across every computer in an Active Directory Domain. This powershell script will restart a specific service by name domain-wide. Each device will be processed in a serialized nature, one-by-one.

Under Connstruction

This document is under construction and not generalized for general purpose use yet. Manual work needs to be done to repurpose this script for general usage.

# Clear the screen before running the script
Clear-Host
Write-Host "Starting Domain-Wide Service Restart" -ForegroundColor Green

# Main Script -------------------------------------------------------------------------------------------------------------------------

# Get a list of all servers from Active Directory
Write-Host "Retrieving server list from Active Directory..."
$servers = Get-ADComputer -Filter * -Property OperatingSystem | Where-Object {
    $_.OperatingSystem -like "*Server*"
} | Select-Object -ExpandProperty Name

# Loop through all servers and start the 'cagservice' service
foreach ($server in $servers) {
    Write-Host ("Attempting to start 'cagservice' on " + $server + "...")
    try {
        Invoke-Command -ComputerName $server -ScriptBlock {
            Start-Service -Name cagservice -ErrorAction Stop
            Write-Host "'cagservice' started successfully on $env:COMPUTERNAME"
        } -ErrorAction Stop
    } catch {
        Write-Host ("Failed to start 'cagservice' on " + $server + ": " + $_.Exception.Message) -ForegroundColor Red
    }
}

Write-Host "Script execution completed." -ForegroundColor Green