【问题标题】:How to check the start type of a windows service is "auto" or "auto-delayed" using Powershell 5 in windows server 2012如何在 Windows Server 2012 中使用 Powershell 5 检查 Windows 服务的启动类型是“自动”还是“自动延迟”
【发布时间】:2019-12-09 21:30:51
【问题描述】:

在维护期间,在我停止 Windows 服务之前,我需要将其启动类型设置为手动。稍后我需要将其切换回原来的启动类型。所以我需要在停止服务之前知道启动类型。

在 Windows 10 中,我知道有一个名为“DelayedAutoStart”的属性,但在 Windows Server 2012 中似乎不可用。如何在 Powershell 中获取服务的启动类型?

我在 Windows Server 2012 上使用 Powershell 5.1。

【问题讨论】:

    标签: powershell delay get-wmiobject


    【解决方案1】:

    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"
    

    【讨论】:

    • 非常感谢您的回答。是否可以在 sc.exe 中使用通配符进行查询?或者是否可以通过管道将服务名称传递给 sc.exe,例如使用 get-service 获取服务列表,然后将其传递给 sc.exe?
    • 嗨,吉姆,是的,我认为最好的方法是使用 Get-Service cmdlet,然后遍历它返回的服务。 Get-Service 返回一个具有属性ServiceName 的对象,该属性与使用 sc.exe 查询时需要使用的名称相同。我将用一个获取每个服务的启动类型的示例来更新我的答案。如果需要,您可以从那里对Get-Service cmdlet 应用过滤器以缩小范围。
    猜你喜欢
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 2013-11-07
    相关资源
    最近更新 更多