Search code examples
powershelldelayget-wmiobject

How to check the start type of a windows service is "auto" or "auto-delayed" using Powershell 5 in windows server 2012


During maintenance, before I stop a Windows service, I need set its start type to Manual. Later I need switch it back to its original start type. So I need know the start type before I stop a service.

In Windows 10, I know there is a property called "DelayedAutoStart", but it seems not available in Windows Server 2012. How can I get the start type of a service in Powershell?

I am using Powershell 5.1 on Windows Server 2012.


Solution

  • Here is a good post with a few approaches to handle the DelayedAutoStart property of a Windows service.

    For your version of PowerShell, you're best off utilizing sc.exe.

    Querying service start type

    You can query for a services start type using sc.exebut the information is returned as text, not PowerShell objects so you have to do some text manipulation. I hacked together a quick one-liner that can get the start type for a service given a name.

    sc.exe qc "SERVICE_NAME" | Select-String "START_TYPE" | ForEach-Object { ($_ -replace '\s+', ' ').trim().Split(" ") | Select-Object -Last 1 }
    

    Here is an example where I utilize it in conjunction with a loop to get the state of every service on the machine.

    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 } 
    }
    

    Setting service start type

    You can set the start type of a service doing something similar to the following...

    sc.exe config NameOfTheService start= delayed-auto
    

    or wrapping sc.exe in PowerShell...

    $myArgs = 'config "{0}" start=delayed-auto' -f 'TheServiceName'
    Start-Process -FilePath sc.exe -ArgumentList $myArgs
    

    As of PowerShell 6.0, they've added the support for AutomaticDelayedStart, however since you're using PowerShell 5.1 this doesn't apply (but it may for other readers).

    Set-Service -Name "Testservice" –StartupType "AutomaticDelayedStart"