Posted On January 25, 2022

PowerShell: Set Service Startup Mode

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Set Service Startup Mode
# setServiceStartupMode.ps1
# Set auto start and restart upon failures

$computernames=@(
    'TESTWINDOWS001',
    'TESTWINDOWS002'
)

$serviceName='windows_exporter'
$startupType='Automatic'
$resets=30
$restartWaitMs=100000

function setServiceStartup{
    param(
        $serviceName='windows_exporter',
        $startupType='Automatic',
        $resets=30,
        $restartWaitMs=100000
    )
    $null=& sc.exe failure $serviceName reset= $resets actions= restart/$restartWaitMs/restart/$restartWaitMs/""/$($restartWaitMs*3)
    Set-Service -Name $serviceName -StartupType $startupType
    write-host "$env:computername now has $servicename set to automatically run and reset at $resets and restart wait-time of $restartWaitMs ms."
    if((get-service $serviceName).Status -eq 'Running'){
        write-host "$serviceName status is Running"
    }else{
        write-warning "$serviceName status is NOT Running"
    }
}

foreach ($computername in $computernames){
    invoke-command -computername $computername {
        param($setServiceStartup,$serviceName,$startupType,$resets,$restartWaitMs)
        [scriptblock]::create($setServiceStartup).invoke($serviceName,$startupType,$resets,$restartWaitMs)
    } -Args ${function:setServiceStartup},$serviceName,$startupType,$resets,$restartWaitMs
}

Set Failure Restarts

# Currently, Legacy commands must be used as PowerShell doesn't yet have such function
$servicename='TrustedInstaller'
& sc.exe failure $serviceName reset= 30 actions= restart/300000/restart/300000/""/300000

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

How To Improve WordPress Website Rendering Speed

These are the recommended plug-ins to enable caching, database cleaning, image compressing, and minify codes…

PowerShell: Get All Hyper-V Servers in the Domain or Forest

This is a working version to correct my previous codes posted somewhere on this site…

PowerShell: Rebooting a List of Computers

Recommended Method to Process a List of Computers: $computernames='web01','web02','web03' restart-computer -computername $computernames -force -wait Get-WmiObject…