Skip to content

Commit 756c4bd

Browse files
committed
[Tweaks] Conditionally determine when to use sc and Set-Service
1 parent becfba6 commit 756c4bd

1 file changed

Lines changed: 14 additions & 2 deletions

File tree

functions/private/Set-WinUtilService.ps1

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,20 @@ Function Set-WinUtilService {
2424
# Check if the service exists
2525
$service = Get-Service -Name $Name -ErrorAction Stop
2626

27-
# Service exists, proceed with changing properties
28-
$service | Set-Service -StartupType $StartupType -ErrorAction Stop
27+
# Service exists, proceed with changing properties -- while handling auto delayed start for PWSH 5
28+
if (($PSVersionTable.PSVersion.Major -lt 7) -and ($StartupType -eq "AutomaticDelayedStart")) {
29+
# Auto delayed start doesn't work with PWSH 5. That startup type is a combination of both the Automatic startup type,
30+
# and an additional DWORD value for delayed start. That's how the SCM defines it. For this, we'll go with sc
31+
#
32+
# PWSH 5 uses a built-in enum for service start types: System.ServiceProcess.ServiceStartMode (https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicestartmode?view=net-10.0-pp)
33+
# PWSH 7 uses a custom enum for service start types: Microsoft.PowerShell.Commands.ServiceStartupType (https://learn.microsoft.com/en-us/dotnet/api/microsoft.powershell.commands.servicestartuptype?view=powershellsdk-7.4.0)
34+
#
35+
# ---- That's why this doesn't work on the former!
36+
37+
sc.exe config $Name start=delayed-auto
38+
} else {
39+
$service | Set-Service -StartupType $StartupType -ErrorAction Stop
40+
}
2941
} catch [System.ServiceProcess.ServiceNotFoundException] {
3042
Write-Warning "Service $Name was not found"
3143
} catch {

0 commit comments

Comments
 (0)