Sc changeserviceconfig ошибка 5

I want to stop the service run automatically when system boots.

For specific information, I’m logged in with «administrator» account.
And opened cmd with «run as administrator»

here’s the log on cmd.

C:\>sc config AppIDSvc start= auto
[SC] ChangeServiceConfig SUCCESS

C:\>sc config AppIDSvc start= demand
[SC] ChangeServiceConfig FAILED 5:

Access is denied.

I don’t understand why I can change startup type to auto but cannot to demand.

Any ideas?

assylias's user avatar

assylias

322k82 gold badges660 silver badges783 bronze badges

asked Jan 25, 2018 at 0:30

Pandol's user avatar

You can just hack the registry: (1=Sys,2=Auto,3=Manual,4=Disabled)

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\WSService\Start  =  4

answered Nov 14, 2020 at 19:17

user1388706's user avatar

1

Run cmd.exe as administrator by right clicking on CMD and selecting Run as Administratoror if Windows 8 or 10, right click Start and select Command Prompt (Admin) then in cmd.exe and type:

net user administrator /active:yes

in the same cmd.exe retry:

sc config AppIDSvc start= demand

Which should return:

[SC] ChangeServiceConfig SUCCESS

If however it still gives the access denied error, please Restart the Computer and then run cmd.exe as Administrator and then retry:

sc config AppIDSvc start= demand

answered Jan 25, 2018 at 8:00

Gerhard's user avatar

GerhardGerhard

22.8k7 gold badges27 silver badges43 bronze badges

I want to stop the service run automatically when system boots.

For specific information, I’m logged in with «administrator» account.
And opened cmd with «run as administrator»

here’s the log on cmd.

C:\>sc config AppIDSvc start= auto
[SC] ChangeServiceConfig SUCCESS

C:\>sc config AppIDSvc start= demand
[SC] ChangeServiceConfig FAILED 5:

Access is denied.

I don’t understand why I can change startup type to auto but cannot to demand.

Any ideas?

assylias's user avatar

assylias

322k82 gold badges660 silver badges783 bronze badges

asked Jan 25, 2018 at 0:30

Pandol's user avatar

You can just hack the registry: (1=Sys,2=Auto,3=Manual,4=Disabled)

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\WSService\Start  =  4

answered Nov 14, 2020 at 19:17

user1388706's user avatar

1

Run cmd.exe as administrator by right clicking on CMD and selecting Run as Administratoror if Windows 8 or 10, right click Start and select Command Prompt (Admin) then in cmd.exe and type:

net user administrator /active:yes

in the same cmd.exe retry:

sc config AppIDSvc start= demand

Which should return:

[SC] ChangeServiceConfig SUCCESS

If however it still gives the access denied error, please Restart the Computer and then run cmd.exe as Administrator and then retry:

sc config AppIDSvc start= demand

answered Jan 25, 2018 at 8:00

Gerhard's user avatar

GerhardGerhard

22.8k7 gold badges27 silver badges43 bronze badges

I want to stop the service run automatically when system boots.

For specific information, I’m logged in with «administrator» account.
And opened cmd with «run as administrator»

here’s the log on cmd.

C:>sc config AppIDSvc start= auto
[SC] ChangeServiceConfig SUCCESS

C:>sc config AppIDSvc start= demand
[SC] ChangeServiceConfig FAILED 5:

Access is denied.

I don’t understand why I can change startup type to auto but cannot to demand.

Any ideas?

assylias's user avatar

assylias

319k78 gold badges658 silver badges776 bronze badges

asked Jan 25, 2018 at 0:30

Pandol's user avatar

You can just hack the registry: (1=Sys,2=Auto,3=Manual,4=Disabled)

HKEY_LOCAL_MACHINESYSTEMControlSet001ServicesWSServiceStart  =  4

answered Nov 14, 2020 at 19:17

user1388706's user avatar

1

Run cmd.exe as administrator by right clicking on CMD and selecting Run as Administratoror if Windows 8 or 10, right click Start and select Command Prompt (Admin) then in cmd.exe and type:

net user administrator /active:yes

in the same cmd.exe retry:

sc config AppIDSvc start= demand

Which should return:

[SC] ChangeServiceConfig SUCCESS

If however it still gives the access denied error, please Restart the Computer and then run cmd.exe as Administrator and then retry:

sc config AppIDSvc start= demand

answered Jan 25, 2018 at 8:00

Gerhard's user avatar

GerhardGerhard

22.4k7 gold badges27 silver badges42 bronze badges

В этой статье мы поговорим о каталоге WinSxS в Windows, причинах его постоянного роста и способах очистки. Каталог C:windowsWinSxS является хранилищем компонентов Windows. В этом каталоге хранятся dll библиотеки, бинарные и xml файлы, необходимые для установки и работы различных ролей и компонентов Windows. Каждый раз когда вы устанавливаете обновления Windows (это происходит ежемесячно), новая версия обновляемого компонента устанавливается в систему, а старая сохраняется в хранилище компонентов WinSxS (это необходимо для обеспечения совместимости и возможности “отката“ к старым версиям компонентов при удалении проблемного обновления).

Со временем размер каталога WinSxS постоянно увеличивается. Причем его размер ничем не ограничен (хотя на практике размер папки WinSxS в Windows 10 редко превышает 15-20 Гб.)

каталог WinSxS в windows10

В этой статье мы рассмотрим наиболее безвредные способы очистки папки WinSxS в Windows 10 и Windows Server.

  • Оптимизация хранилища компонентов и удаление старых версий компонентов, оставшихся после установки обновлений Windows;
  • Технология Features on Demand (функции по требованию), позволяющая удалить неиспользуемые компоненты Windows с диска;
  • Сжатие файлов в папке WinSxS – способ уменьшить размер каталога WinSxS за счет включения NTFS компрессии.

У многих пользователей возникает естественный вопрос можно ли вручную удалить файлы из папки WinSxS. Ответ на этот вопрос – категоричное НЕТ! Такими действиями с большой долей вероятности вы сломаете свою Windows. И хотя отдельные попытки удаления конкретных файлов из папки WinSxS могут быть удачными, рекомендовать этот способ нельзя.

Содержание:

  • Как узнать реальный размер папки WinSxS в Windows 10?
  • Очистка хранилища компонентов WinSxS в Windows
  • Удаление неиспользуемых компонентов Windows (Windows Server)
  • Включаем NTFS сжатие на папке WinSxS в Windows

Как узнать реальный размер папки WinSxS в Windows 10?

Самый простой способ получить текущий размер каталога WinSxS в Windows, запустить проводник File Explorer и открыть свойства папки %windir%WinSxS (или воспользоваться скриптом PowerShell). Но имейте в виду, что большинство файловых менеджеров (в том числе File Explorer) показывают несколько больший размер каталога WinSxS, чем он занимает на диске.

Дело в том, что в каталоге WinSxS есть большое количество hard links (жестких символических ссылок) на файлы в других системных каталогах. Файловые менеджеры при подсчете размера папки WinSxS учитывают объем файлов, на которые ссылаются жесткие ссылки, а это не корректно.

Чтобы реальный (без учета жестких ссылок) размер папки WinSxS, воспользуйтесь утилитой SysInternal du:

du -v c:windowswinSXS

получить реальный размер каталога winsxs с помощью утилиты du.exe

Но проще всего проанализировать размер хранилища компонентов в папке WinSxS с помощью команды DISM:

Dism.exe /Online /Cleanup-Image /AnalyzeComponentStore

Dism.exe Cleanup Image-AnalyzeComponentStore

Разберемся, что возвращает данная команда:

Размер хранилища компонентов по данным проводника : 5.70 GB (это размер хранилища с учета жестких ссылок, который отображается в проводнике)
Фактический размер хранилища компонентов : 5.49 GB (реальный размер хранилища компонентов за исключением жестких ссылок)
Совместно с Windows : 3.12 GB (обязательные файлы системы, не могут быть удалены)
Резервные копии и отключенные компоненты : 2.12 GB (устаревшие файлы компонентов, которые нужны на случай проблем с установленными обновлениями)
Кэш и временные данные : 245.87 MB (файлы используются для ускорения работы системы обслуживания)
Дата последней очистки : 2018-07-31 12:45:23
Число освобождаемых пакетов : 10 (файлы, которые обновились после установки обновлений Windows, они будут удалены при очистке хранилища)
Рекомендуется очистка хранилища компонентов : Да

Как вы видите, в данном случае можно уменьшить размер каталога WinSxS на 2.1 Гб + 250 Мб.

Очистка хранилища компонентов WinSxS в Windows

Самый быстрый и простой способ освободить место в хранилище компонентов Windows (т.е. очистить папку WinSxS) – оптимизация хранилища командой:

Dism.exe /Online /Cleanup-Image /StartComponentCleanup

Dism.exe Cleanup Image StartComponentCleanup

Опция Dism /StartComponentCleanup поддерживается во всех версиях Windows, начиная с Windows 8/Windows Server.

После окончания очистки проверьте текущий размер хранилища компонентов:

Dism.exe /Online /Cleanup-Image /AnalyzeComponentStore

В моем примере это помогло уменьшить размер папки WinSxS на 2,5 Гб.

С помощью еще одного параметра /ResetBase вы можете удалить все предыдущие версии компонентов, оставшиеся после установки обновлений Windows. После этого вы не сможете удалить установленные обновления или Service Pack, а в панели обновлений
appwiz.cpl
у обновлений пропадет кнопка «Удалить»).

Чтобы очистить старые версии компонентов, выполните:

Dism.exe /Online /Cleanup-Image /StartComponentCleanup /ResetBase

В Windows 7 и Windows Server 2008 R2 для очистки старых версий компонентов, оставшихся после установки сервис пака, использовался еще один параметр DISM:

dism /online /Cleanup-Image /spsuperseded

Также вы можете удалить устаревшие обновления с помощью мастера очистки диска. Выполните команду cleanmgr c правами администратора.

В окне утилиты выберите диск и в следующем окне нажмите кнопку «Очистить системны файлы».

cleanmgr windows 10 Очистить системны файлы

Далее выберите опцию “Файлы журнала обновления Windows» и нажмите ОK. Утилита очистки диска покажет сколько места вы можете освободить, удалив файлы журнала старых обновлений Windows. В моем примере это 427 Мб.

удалить файлы журнала обновлений windows

После окончания очистки хранилища с помощью DISM проверьте сколько освободилось места на диске.

В планировщике задания Windows 10 и Windows Server 2016 есть специальное задание автоматического обслуживания, которое регулярно выполняет оптимизацию и очистку каталога WinSxS (выполняется действия, аналогичные команде dism с ключом StartComponentCleanup). Это задание StartComponentCleanup находится в разделе MicrosoftWindowsServicing. Данное задание запускается в фоновом режиме и автоматически удаляет версии компонентов старше 30 дней, которое были заменены более новыми версиями.

Можно запустить это задание вручную так:

schtasks.exe /Run /TN "MicrosoftWindowsServicingStartComponentCleanup"

задание планировщика StartComponentCleanup - очистка компонентов

Удаление неиспользуемых компонентов Windows (Windows Server)

В статье Безопасная очистка папки WinSxS в Windows Server 2016/2012 мы рассмотрели функцию Features on Demand (функции по требованию), предоставляющую возможность удаления с диска бинарных файлов неиспользуемых ролей и компонентов из каталога WinSxS. Для этого в Windows Server используется командлет PoweShell Uninstall-WindowsFeature.

В Windows 10 командлет Uninstall-WindowsFeature отсуствует, и для удаления компонентов Windows из образа нужно использовать DISM.

DISM в отличии от Uninstall-WindowsFeature не удаляет зависимые компоненты.

Полный список доступных функций в образе Windows 10 можно получить с помощью команды:
DISM.exe /Online /English /Get-Features /Format:Table

windows 10 dism get-features список установленных компонентов

Чтобы удалить, например компонент TelnetClient с диска (из каталога WinSxS), выполните команду:
DISM.exe /Online /Disable-Feature /Featurename:TelnetClient /Remove

DISM Disable-Feature Remove

Если еще раз вывести список всех доступных функций по требованию в Windows, вы увидите, что статус компонента изменится на Disabled with Payload Removed.

Таким образом в Windows можно существенно уменьшить размер папки WinSxS, удалив с диска неиспользуемые компоненты. Единственный нюанс, это вариант очистки каталога WinSxS подойдет для достаточной продвинутых пользователей, которые разбираются в компонентах Windows 10 и их назначении.

Включаем NTFS сжатие на папке WinSxS в Windows

Еще один способ уменьшить размера каталога WinSxS в Windows 10 – сжать содержимое каталога на уровне файловой системы NTFS.

  1. Откройте командную строку с правами администратора;
  2. Остановите и отключите службы Windows Installer и Windows Module Installer:
    sc stop msiserver
    
    sc stop TrustedInstaller
    
    sc config msiserver start= disabled
    
    sc config TrustedInstaller start= disabled
  3. Создайте резервную копию списков доступа (ACL) назначенных на файлы и папки в каталоге WinSxS с помощью утилиты icacls. Резервная копия ACL представляет собой обычной текстовый файл, в котором указаны все файлы и каталоги и назначенные на них NTFS разрешения (в дальнейшем этот файл понадобиться для восстановления оригинальных ACL):
    icacls "%WINDIR%WinSxS" /save "%WINDIR%WinSxS_NTFS.acl" /t

    создаем резевную копию разрешений каталога winsxs

  4. Назначьте себя владельцем папки WinSxS и всех вложенных каталогов:
    takeown /f "%WINDIR%WinSxS" /r
  5. Предоставьте своей учетной записи полные права на каталог WinSxS:
    icacls "%WINDIR%WinSxS" /grant "%USERDOMAIN%%USERNAME%":(F) /t
  6. Теперь можно выполнить сжатие файлов в каталоге WinSxS с помощью команды compact. Т.к. часть файлов может использоваться Windows, нужно указать параметр /i. Иначе сжатие будет остановлено на первом же занятом файле (в Windows 10 можно использовать более прогрессивное LZX сжатие):
    compact /s:"%WINDIR%WinSxS" /c /a /i *

    Сжимаем содержимое каталога winsxs

  7. Теперь нужно восстановить TrustedInstaller как владельца каталога WinSxS:
    icacls "%WINDIR%WinSxS" /setowner "NT SERVICETrustedInstaller" /t
  8. И вернуть оригинальные NTFS разрешения на каталог WinSxS из резервной копии ACL:
    icacls "%WINDIR%" /restore "%WINDIR%WinSxS_NTFS.acl"
  9. Измените типа тип запуска служб Windows Installer и Windows Module Installer:
    sc config msiserver start= demand
    
    sc config TrustedInstaller start= demand

Проверьте текущий размер каталога WinSxS.

уменьшить размер каталога winsxs в windows10 с помощью сжатия

Как вы видите, в нашем примере размер папки WinSxS за счет сжатия уменьшился с 9,36 Гб до 6,5 Гб (примерно на треть). Неплохо, особо для небольшого по размеру SSD-диска.

Указанные команды можно выполнять по отдельности (так проще контролировать успешность выполнения каждой из них), либо можно объединить все операции в один файл скрипт. Вы можете скачать готовый bat файл для сжатия WinSxS здесь compress_winsxs.bat

Данный скрипт нужно запускать периодически, т.к. в каталоге WinSxS будут появляться новые «несжатые» файлы после установки новых обновлений Windows и программ.

На что может повлиять сжатие каталога WinSxS? Windows работает со сжатыми файлами в прозрачном режиме, однако при обработке таких файлов, ей может понадобиться дополнительное время на их декомпрессию/компрессию. Это может вызвать небольшое замедление при установке компонентов Windows или обновлений. Однако для современных процессоров (CPU) операция компрессии/декомпрессии файлов выполняется практически мгновенно, так что реального уменьшения скорости пользователь даже не заметит.

crobertson

Sep 17, 2008
15
0
18,510
0
  • #1

I’ve been able to run this batch file before but when I run this one command in a batch file I get an «Access denied» error.
First the batch file

@echo off
:start
SC config Alerter start= auto
pause

I can run sc config Alerter start= auto in the command prompt and it works, but it won’t work in a batch file! I know I have the syntax correct. I’ve tried «» around the service name and the startup type, and this is verbatum from some sites I have visted.

I have XP pro and am running as administrator.

The error I receive is;
[SC] ChangeServiceConfig FAILED 5:
Access is denied.

I’ve searched for about 4 hours now and have not resolved this issue.

tigsounds

May 29, 2010
3,922
1
23,460
227
  • #2

I just ran your batch file and had success.

Right-click the batch file and click properties and the security tab.

My «group or users names» is set to «Everyone» by default with Full Control granted.

Check yours.

  • Advertising
  • Cookies Policies
  • Privacy
  • Term & Conditions
  • Topics

Я хочу остановить автоматический запуск службы при загрузке системы.

Для конкретной информации, я вошел в систему с учетной записью «администратор». И открыл cmd с «запустить от имени администратора»

Вот журнал cmd.

C:>sc config AppIDSvc start= auto
[SC] ChangeServiceConfig SUCCESS

C:>sc config AppIDSvc start= demand
[SC] ChangeServiceConfig FAILED 5:

Access is denied.

Я не понимаю, почему я могу изменить тип запуска на автоматический, но не могу требовать.

Любые идеи?

2 ответа

Вы можете просто взломать реестр: (1=Sys,2=Auto,3=Manual,4=Disabled)

HKEY_LOCAL_MACHINESYSTEMControlSet001ServicesWSServiceStart  =  4


4

user1388706
14 Ноя 2020 в 22:17

Запустите cmd.exe от имени администратора, щелкнув правой кнопкой мыши CMD и выбрав Run as Administratorили, если Windows 8 или 10, щелкните правой кнопкой мыши Пуск и выберите Command Prompt (Admin), затем в cmd.exe и введите:

net user administrator /active:yes

В той же cmd.exe повторной попытке:

sc config AppIDSvc start= demand

Который должен вернуться:

[SC] ChangeServiceConfig УСПЕШНО

Однако, если он по-прежнему выдает ошибку access denied, перезагрузите компьютер, а затем запустите cmd.exe от имени администратора, а затем повторите попытку:

sc config AppIDSvc start= demand


0

Gerhard
25 Янв 2018 в 11:00

Hi,

Ok, here I am porting my service to Vista.
I’m using ChangeServiceConfig2() to make sure the service is restarted if it fails, but I can’t get my code to work! let me show you what I’m talking about (this is a cropped version of the code, I close the handles afterwards):

    BOOL        result=0;
    SERVICE_FAILURE_ACTIONSA failureActions;
    SC_ACTION    actions;
    int e;
    actions.Type = 1; // SC_ACTION_RESTART
    actions.Delay = 10000;
    failureActions.dwResetPeriod = 10;
    failureActions.lpRebootMsg = «»;
    failureActions.lpCommand = NULL;
    failureActions.cActions = 1;
    failureActions.lpsaActions = &actions;

    if (!Load_ADVAPI32() || !P_OpenSCManagerA || !P_CreateServiceA)
        return 0;

    SchSCManager = P_OpenSCManagerA(server_name, NULL, SC_MANAGER_ALL_ACCESS );
    if(SchSCManager == NULL)
        return 0;
    schService = P_OpenServiceA(SchSCManager, driver_name, SERVICE_CHANGE_CONFIG);
    if (schService != NULL)
    {
        if (!P_ChangeServiceConfig2A(schService, 2, &failureActions))
        {
            e = GetLastError();
        }
    }

    result=1;

And, when I’m stepping through the code, the code flow enters into that final condition where
the P_ChangeServiceConfig2A call fails, and GetLastError() returns 5: ERROR_ACCESS_DENIED.

This fails on Windows XP and Windows 2003 as well. I’m running as an admin with UAC turned off, and I can also make sure that I am elevated because a few calls before, when I’m creating the service, everything works ok.

This fails with P_ChangeServiceConfig2W as well with the same problems.

Has anyone worked with this function and got it working before?

cheers,

Oscar

After doing a fresh install of Windows, disabling unused Windows Services is one of the time-consuming tasks you perform. Once configured, you can back up the service startup state using a Script so that it can be used for subsequent installations or if you need to automate the task on several computers.

Services state backups can also help when you troubleshoot Windows services and want to quickly roll back the changes you made.

Here is a Windows Services startup configuration backup VBScript.  The script backs up the startup state of all Services by outputting the services configuration into two file formats — .reg (registration entries) and .bat (Windows Batch file) for you to restore the services configuration later.


'Description: This script backs up the Windows Services startup configuration to Batch & REG files.
'For Windows 10/11, Windows Server 2016
'© 2016-2022  Ramesh Srinivasan
'Website: https://www.winhelponline.com/blog/
'Created: 2016
'Revised: July 30, 2022

Option Explicit
If WScript.Arguments.length = 0 Then
   Dim objShell : Set objShell = CreateObject("Shell.Application")
   objShell.ShellExecute "wscript.exe", Chr(34) & _
   WScript.ScriptFullName & Chr(34) & " uac", "", "runas", 1
Else
   Dim WshShell, objFSO, objFile, sNow, iSvcType, iStartupType, iSvcCnt, iPerUserSvcCnt
   Dim sREGFile, sBATFile, r, b, objWMIService, colListOfServices, objService, sSvcKey
   Dim sStartState, sSvcName, sSkippedSvc
   Set WshShell = CreateObject("Wscript.Shell")
   Set objFSO = Wscript.CreateObject("Scripting.FilesystemObject")
   Set objFile = objFSO.GetFile(WScript.ScriptFullName)
   
   'Set files names for REG and Batch files
   sNow = Year(Date) & Right("0" & Month(Date), 2) & Right("0" & Day(Date), 2)
   sREGFile = objFSO.GetParentFolderName(objFile) & "\svc_curr_state_" & sNow & ".reg"
   sBATFile = objFSO.GetParentFolderName(objFile) & "\svc_curr_state_" & sNow & ".bat"
   sSvcKey = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\"
   
   Set r = objFSO.CreateTextFile (sREGFile, True)
   r.WriteLine "Windows Registry Editor Version 5.00"
   r.WriteBlankLines 1
   r.WriteLine ";Services Startup Configuration Backup " & Now
   r.WriteBlankLines 1
   
   Set b = objFSO.CreateTextFile (sBATFile, True)
   b.WriteLine "@echo Restore Service Startup State saved at " & Now
   b.WriteBlankLines 1
   
   iSvcCnt=0
   iPerUserSvcCnt=0
   
   Set objWMIService = GetObject("winmgmts:" _
   & "{impersonationLevel=impersonate}!\\" & "." & "\root\cimv2")
   
   Set colListOfServices = objWMIService.ExecQuery ("Select * from Win32_Service")
   
   For Each objService In colListOfServices
      iSvcCnt=iSvcCnt + 1
      sStartState = lcase(objService.StartMode)
      sSvcName = objService.Name
      
      'Check if it's a per-user service. The service type will be "Unknown"
      If objService.ServiceType = "Unknown" Then
         'Get the corresponding Template Service's name from the Per-user service name
         Dim sSvcTemplateName
         sSvcTemplateName = Split(sSvcName, "_")
         
         On Error Resume Next
         iSvcType = WshShell.RegRead (sSvcKey & sSvcTemplateName(0) & "\Type")
         On Error GoTo 0
         If Err.number = 0 Then
            'Template service will be of type 96 or 80.
            If iSvcType = "96" Or iSvcType = "80" Then
               'It's a Per-user service
               iPerUserSvcCnt = iPerUserSvcCnt + 1
               sSvcName = sSvcTemplateName(0)
            End If
         End If
      End If
      
      r.WriteLine "[" & sSvcKey & sSvcName & "]"
      
      'If the service name contains spaces, enclose it in double quotes
      If InStr(sSvcName, " ") > 0  Then
         sSvcName = """" & sSvcName & """"
      End If
      
      Select Case sStartState
         Case "boot"
         
         r.WriteLine chr(34) & "Start" & Chr(34) & "=dword:00000000"
         b.WriteLine "sc.exe config " & sSvcName & " start= boot"
         
         Case "system"
         r.WriteLine chr(34) & "Start" & Chr(34) & "=dword:00000001"
         b.WriteLine "sc.exe config " & sSvcName & " start= system"
         
         Case "auto"
         'Check if it's Automatic (Delayed start)
         r.WriteLine chr(34) & "Start" & Chr(34) & "=dword:00000002"
         If objService.DelayedAutoStart = True Then
            r.WriteLine chr(34) & "DelayedAutostart" & Chr(34) & "=dword:00000001"
            b.WriteLine "sc.exe config " & sSvcName & " start= delayed-auto"
         Else
            r.WriteLine chr(34) & "DelayedAutostart" & Chr(34) & "=-"
            b.WriteLine "sc.exe config " & sSvcName & " start= auto"
         End If
         
         Case "manual"
         
         r.WriteLine chr(34) & "Start" & Chr(34) & "=dword:00000003"
         b.WriteLine "sc.exe config " & sSvcName & " start= demand"
         
         Case "disabled"
         
         r.WriteLine chr(34) & "Start" & Chr(34) & "=dword:00000004"
         b.WriteLine "sc.exe config " & sSvcName & " start= disabled"
         
         Case "unknown"	sSkippedSvc = sSkippedSvc & vbcrlf & sSvcName
         
         'Case Else
      End Select
      r.WriteBlankLines 1      
   Next
   
   If trim(sSkippedSvc) <> "" Then
      WScript.Echo iSvcCnt & "  - Total # of Services." & _
      "(including " & iPerUserSvcCnt & " Per-user Services)" & _
      vbCrLf & vbCrLf & "The following services could not be backed up:" & _
      vbcrlf & vbCrLf & sSkippedSvc
   Else
      WScript.Echo iSvcCnt & " Services found " & _
      "(including " & iPerUserSvcCnt & " Per-user Services)" & _
      " and their startup configuration has been backed up."
   End If
   
   r.Close
   b.WriteLine "@pause"
   b.Close
   'WshShell.Run "notepad.exe " & sREGFile
   'WshShell.Run "notepad.exe " & sBATFile
   Set objFSO = Nothing
   Set WshShell = Nothing
End If

How to Use the VBScript?

  1. Copy the above lines of code to Notepad
  2. Save the file with .vbs extension — e.g., services_startup_config_backup.vbs.
  3. Double-click to run the script.

The script relaunches itself as administrator (elevated) and queries the list of Windows services and their startup type configuration. The results are written to .reg and .bat files for later restoration. The two files are created in the same folder as the script.

backup services script message box

The output files will have the prefix svc_curr_state_ and then followed by the current date in yyyymmdd format — e.g., svc_curr_state_20190706.reg & svc_curr_state_20190706.bat

backup and restore windows services startup type configuration

Note: The script also takes into consideration whether a service is configured for a delayed start or not. For services with an Automatic (delayed start) startup type, an additional registry value named DelayedAutoStart is used. If DelayedAutoStart is set to 1 and the Start value is set to 2 (Automatic), then the service will be configured as Automatic (delayed start). And the Batch file will have the delayed-auto as the startup mode for those services.

Restoring the Services Startup type configuration

To restore the services startup type configuration from the backup, choose one of the two formats.

Please use Windows Safe mode to restore the services startup configuration from .reg or Batch file. Safe mode is highly recommended for this task.

.reg file

If you use the .reg file to restore the service startup preferences, you’ll need to restart Windows after applying the .reg file for the services configuration to refresh. This is the preferred method, though.

.bat file

The Batch file contains SC commands that will change the startup configuration of the services in real time. You don’t require a restart if using the method. Make sure you run the Batch file from an admin Command Prompt window.

backup and restore windows services startup type configuration

Error 5 when restoring Services configuration from Batch file?

For some services, you may encounter errors like [SC] ChangeServiceConfig FAILED 5: or similar. This can be due to tightened service permissions or security descriptors which lock down services, or your antivirus program may be blocking it. In that case, launch a Command Prompt window under the LOCAL SYSTEM account or TrustedInstaller and run the Batch file.

If your antivirus program is stopping you from modifying certain services, you can attempt to run the file from Safe Mode.

Per-user services

The Services MMC in Windows 10 and 11, shows you many services whose names have an underscore (_) and are followed by some numbers. These numbers (suffixes) represent the login session’s unique identifier (LUID) that doesn’t match with that of other computers. Here are some examples:

  • AarSvc_8561415
  • BcastDVRUserService_8561415
  • BluetoothUserService_8561415
  • CaptureService_8561415
  • cbdhsvc_8561415
  • CDPUserSvc_8561415
  • ConsentUxUserSvc_8561415
  • CredentialEnrollmentManagerUserSvc_8561415
  • DeviceAssociationBrokerSvc_8561415
  • DevicePickerUserSvc_8561415
  • DevicesFlowUserSvc_8561415
  • LxssManagerUser_8561415
  • MessagingService_8561415
  • OneSyncSvc_8561415
  • PimIndexMaintenanceSvc_8561415
  • PrintWorkflowUserSvc_8561415
  • UnistoreSvc_8561415
  • UserDataSvc_8561415
  • WpnUserService_8561415

If a user tries to modify the above per-user services configuration using the SC.exe command, it causes the error ChangeServiceConfig FAILED 87: The parameter is incorrect. And, the LUID suffix 8561415 in the above service names won’t be the same on other computers. For more information on Per-user services, see the Microsoft article Per-user services in Windows 10/11 and Windows Server.

The script aptly backs up the service templates instead of the per-user services. For instance, the per-user service “WpnUserService_8561415” borrows the configuration from its template service “WpnUserService“. Similarly, OneSyncSvc_8561415 ‘s template service is OneSyncSvc, and so on. Backing up the template service configuration is the correct way.

For older versions of Windows

For Windows versions earlier than Windows 10 (Windows Vista through Windows 8.1), use the script services_conf_backup.zip. Note that the older script doesn’t support the Automatic (delayed start) start type — because of a WMI limitation. It treats Automatic and Automatic (delayed start) as the same.


One small request: If you liked this post, please share this?

One «tiny» share from you would seriously help a lot with the growth of this blog.
Some great suggestions:

  • Pin it!
  • Share it to your favorite blog + Facebook, Reddit
  • Tweet it!

So thank you so much for your support. It won’t take more than 10 seconds of your time. The share buttons are right below. :)


Hi,

Ok, here I am porting my service to Vista.
I’m using ChangeServiceConfig2() to make sure the service is restarted if it fails, but I can’t get my code to work! let me show you what I’m talking about (this is a cropped version of the code, I close the handles afterwards):

    BOOL        result=0;
    SERVICE_FAILURE_ACTIONSA failureActions;
    SC_ACTION    actions;
    int e;
    actions.Type = 1; // SC_ACTION_RESTART
    actions.Delay = 10000;
    failureActions.dwResetPeriod = 10;
    failureActions.lpRebootMsg = «»;
    failureActions.lpCommand = NULL;
    failureActions.cActions = 1;
    failureActions.lpsaActions = &actions;

    if (!Load_ADVAPI32() || !P_OpenSCManagerA || !P_CreateServiceA)
        return 0;

    SchSCManager = P_OpenSCManagerA(server_name, NULL, SC_MANAGER_ALL_ACCESS );
    if(SchSCManager == NULL)
        return 0;
    schService = P_OpenServiceA(SchSCManager, driver_name, SERVICE_CHANGE_CONFIG);
    if (schService != NULL)
    {
        if (!P_ChangeServiceConfig2A(schService, 2, &failureActions))
        {
            e = GetLastError();
        }
    }

    result=1;

And, when I’m stepping through the code, the code flow enters into that final condition where
the P_ChangeServiceConfig2A call fails, and GetLastError() returns 5: ERROR_ACCESS_DENIED.

This fails on Windows XP and Windows 2003 as well. I’m running as an admin with UAC turned off, and I can also make sure that I am elevated because a few calls before, when I’m creating the service, everything works ok.

This fails with P_ChangeServiceConfig2W as well with the same problems.

Has anyone worked with this function and got it working before?

cheers,

Oscar

Понравилась статья? Поделить с друзьями:
  • Sasplanet ошибка 404
  • Samsung wf702w2bbwq ошибка 3е
  • Sas обработка ошибок
  • Samsung wf6528n7w ошибка he2
  • Sas planet ошибка unable to load maps