Files
winutil/functions/private/Set-WinUtilService.ps1
4b2fe55a7a fix(system): correct service, update repair, and legacy imports (#4966)
* fix(system): correct sc.exe argument syntax, reg deletion, and ipv6 dns guard

* fix(impex): exclude legacy Install metadata from flattened import

* fix(service): throw on non-zero LASTEXITCODE from sc.exe config

* refactor(dns): revert unnecessary ipv6 guard per review feedback

* test(impex): cover legacy config imports

---------

Co-authored-by: WinUtil Contributor <contributor@winutil.local>
Co-authored-by: Chris Titus <contact@christitus.com>
2026-08-19 16:54:24 -05:00

56 lines
2.1 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"
Write-WinUtilLog -Component "Service" -Message "Setting service $Name startup type to $StartupType"
# Check if the service exists
$service = Get-Service -Name $Name -ErrorAction Stop
if (($service.PSObject.Properties.Name -contains "StartType") -and ([string]$service.StartType -eq [string]$StartupType) ) {
Write-Host "Service $Name is already set to $StartupType"
Write-WinUtilLog -Component "Service" -Message "Service $Name startup type is already $StartupType; no change needed."
return
}
# 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
if ($LASTEXITCODE -ne 0) {
throw "sc.exe config failed with exit code $LASTEXITCODE"
}
} else {
$service | Set-Service -StartupType $StartupType -ErrorAction Stop
}
Write-WinUtilLog -Component "Service" -Message "Service $Name startup type set to $StartupType"
} catch {
if ($_.FullyQualifiedErrorId -like "NoServiceFoundForGivenName,*") {
Write-Warning "Service $Name was not found."
Write-WinUtilLog -Level "WARN" -Component "Service" -Message "Service $Name was not found."
} else {
Write-Warning "Unable to set $Name due to unhandled exception."
Write-Warning $_.Exception.Message
Write-WinUtilLog -Level "ERROR" -Component "Service" -Message "Unable to set service $Name to $StartupType`: $($_.Exception.Message)"
}
}
}