Here 是一篇很好的文章,其中介绍了一些处理 Windows 服务的 DelayedAutoStart 属性的方法。
对于您的 PowerShell 版本,您最好使用 sc.exe。
查询服务启动类型
您可以使用sc.exe查询服务启动类型,但信息以文本形式返回,而不是 PowerShell 对象,因此您必须进行一些文本操作。我编写了一个快速的单行代码,可以获取给定名称的服务的启动类型。
sc.exe qc "SERVICE_NAME" | Select-String "START_TYPE" | ForEach-Object { ($_ -replace '\s+', ' ').trim().Split(" ") | Select-Object -Last 1 }
这是一个示例,我将它与循环结合使用来获取机器上每个服务的状态。
foreach($Service in (Get-Service)) {
Write-Host "$($Service.ServiceName)"
sc.exe qc "$($Service.ServiceName)" | Select-String "START_TYPE" | ForEach-Object { ($_ -replace '\s+', ' ').trim().Split(" ") | Select-Object -Last 1 }
}
设置服务启动类型
您可以设置服务的启动类型,执行类似于以下操作...
sc.exe config NameOfTheService start= delayed-auto
或在 PowerShell 中包装 sc.exe...
$myArgs = 'config "{0}" start=delayed-auto' -f 'TheServiceName'
Start-Process -FilePath sc.exe -ArgumentList $myArgs
从 PowerShell 6.0 开始,他们添加了对 AutomaticDelayedStart 的支持,但是由于您使用的是 PowerShell 5.1,这并不适用(但它可能适用于其他读者)。
Set-Service -Name "Testservice" –StartupType "AutomaticDelayedStart"