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

LAMP Stack using Docker

# Install docker and composeyum install docker docker-compose -y# Add user into docker groupusermod -aG…

How to Install SSL Certificate(s) on Various Web Servers

Public facing websites often become become targets of attacks such as eavesdropping, denial of service,…

Quick Script to Test SharePoint Online Credentials

$principle = "[email protected]" $password = 'PASSW0RT' $sharePointUrl = "https://SOMESHAREPOINT.COM/SitePages/Home.aspx" $credential=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $principle,$(ConvertTo-securestring $password…
Other project: DragonCoin.com