winutil/functions/private/Set-WinUtilService.ps1
CodingWonders cfaf139a6a
[Tweaks] Conditionally determine when to use sc and Set-Service (#3761)
* [Tweaks] Conditionally determine when to use sc and Set-Service

* Clean up comments in Set-WinUtilService.ps1

Removed comments explaining the handling of auto delayed start for PWSH 5.

---------

Co-authored-by: Chris Titus <contact@christitus.com>
2025-12-01 14:29:27 -06:00

41 lines
1.2 KiB
PowerShell

Function Set-WinUtilService {
<#
.SYNOPSIS
Changes the startup type of the given service
.PARAMETER Name
The name of the service to modify
.PARAMETER StartupType
The startup type to set the service to
.EXAMPLE
Set-WinUtilService -Name "HomeGroupListener" -StartupType "Manual"
#>
param (
$Name,
$StartupType
)
try {
Write-Host "Setting Service $Name to $StartupType"
# Check if the service exists
$service = Get-Service -Name $Name -ErrorAction Stop
# Service exists, proceed with changing properties -- while handling auto delayed start for PWSH 5
if (($PSVersionTable.PSVersion.Major -lt 7) -and ($StartupType -eq "AutomaticDelayedStart")) {
sc.exe config $Name start=delayed-auto
} else {
$service | Set-Service -StartupType $StartupType -ErrorAction Stop
}
} catch [System.ServiceProcess.ServiceNotFoundException] {
Write-Warning "Service $Name was not found"
} catch {
Write-Warning "Unable to set $Name due to unhandled exception"
Write-Warning $_.Exception.Message
}
}