Как перебрать все службы Windows в пакетном режиме - PullRequest
0 голосов
/ 05 июня 2019

Я пытаюсь создать пакетный скрипт, который меняет типы запуска служб на основе их имен.Но что-то не работает в моем цикле, и я не знаю, почему это не работает :( Пожалуйста, помогите:)

Я уже пытался принять команду, которую я использую в качестве того, что я ищуи прогнал его через cmd.Работает нормально.Однако, когда я вставляю его в свой цикл, он отказывается функционировать.Я довольно новичок в партии, и я не понимаю ...

Это то, что у меня сейчас есть:

@echo off
setlocal enabledelayedexpansion
pause

set "autosvc=;BrokerInfrastructure;BFE;"&REM list of services set to auto
set "delayedautosvc=;BITS;CDPSvc;"&REM list of services set to delayed-auto
set "delayedautosvc=;AxInstSV;AJRouter;"&REM list of services set to manual

for /f "tokens=1 delims=," %%i in ('sc query type= service state= all ') do (
    set tmpry=0
    if "!autosvc:;%%~i;=!" equ "!autosvc!" ( set /a tmpry=1 
    ) else ( if "!delayedautosvc:;%%~i;=!" equ "!delayedautosvc!" ( set /a tmpry=2
    ) else ( if "!demandsvc:;%%~i;=!" equ "!demandsvc!" ( set /a tmpry=3 )
    ) )
    if !tmpry! equ 1 ( echo AUTOMATIC - %%~i )
    if !tmpry! equ 2 ( echo DELAYEDAUTOMATIC - %%~i )
    if !tmpry! equ 3 ( echo MANUAL - %%~i )
    if !tmpry! lss 1 ( echo DISABLE - %%~i )
)
pause

К сожалению, это вывод:

Configuring service settings...
AUTOMATIC - ERROR:  Invalid Option
AUTOMATIC - DESCRIPTION:
AUTOMATIC -         SC is a command line program used for communicating with the
AUTOMATIC -         Service Control Manager and services.
AUTOMATIC - USAGE:
AUTOMATIC -         sc <server> [command] [service name] <option1> <option2>...
AUTOMATIC -         The option <server> has the form "\\ServerName"
AUTOMATIC -         Further help on commands can be obtained by typing: "sc [command]"
AUTOMATIC -         Commands:
AUTOMATIC -           query-----------Queries the status for a service
AUTOMATIC -                           enumerates the status for types of services.
AUTOMATIC -           queryex---------Queries the extended status for a service
AUTOMATIC -                           enumerates the status for types of services.
AUTOMATIC -           start-----------Starts a service.
AUTOMATIC -           pause-----------Sends a PAUSE control request to a service.
AUTOMATIC -           interrogate-----Sends an INTERROGATE control request to a service.
AUTOMATIC -           continue--------Sends a CONTINUE control request to a service.
AUTOMATIC -           stop------------Sends a STOP request to a service.
AUTOMATIC -           config----------Changes the configuration of a service (persistent).
AUTOMATIC -           description-----Changes the description of a service.
AUTOMATIC -           failure---------Changes the actions taken by a service upon failure.
AUTOMATIC -           failureflag-----Changes the failure actions flag of a service.
AUTOMATIC -           sidtype---------Changes the service SID type of a service.
AUTOMATIC -           privs-----------Changes the required privileges of a service.
AUTOMATIC -           managedaccount--Changes the service to mark the service account
AUTOMATIC -                           password as managed by LSA.
AUTOMATIC -           qc--------------Queries the configuration information for a service.
AUTOMATIC -           qdescription----Queries the description for a service.
AUTOMATIC -           qfailure--------Queries the actions taken by a service upon failure.
AUTOMATIC -           qfailureflag----Queries the failure actions flag of a service.
AUTOMATIC -           qsidtype--------Queries the service SID type of a service.
AUTOMATIC -           qprivs----------Queries the required privileges of a service.
AUTOMATIC -           qtriggerinfo----Queries the trigger parameters of a service.
AUTOMATIC -           qpreferrednode--Queries the preferred NUMA node of a service.
AUTOMATIC -           qmanagedaccount-Queries whether a services uses an account with a
AUTOMATIC -                           password managed by LSA.
AUTOMATIC -           qprotection-----Queries the process protection level of a service.
AUTOMATIC -           quserservice----Queries for a local instance of a user service template.
AUTOMATIC -           delete----------Deletes a service (from the registry).
AUTOMATIC -           create----------Creates a service. (adds it to the registry).
AUTOMATIC -           control---------Sends a control to a service.
AUTOMATIC -           sdshow----------Displays a service's security descriptor.
AUTOMATIC -           sdset-----------Sets a service's security descriptor.
AUTOMATIC -           showsid---------Displays the service SID string corresponding to an arbitrary name.
AUTOMATIC -           triggerinfo-----Configures the trigger parameters of a service.
AUTOMATIC -           preferrednode---Sets the preferred NUMA node of a service.
AUTOMATIC -           GetDisplayName--Gets the DisplayName for a service.
AUTOMATIC -           GetKeyName------Gets the ServiceKeyName for a service.
AUTOMATIC -           EnumDepend------Enumerates Service Dependencies.
AUTOMATIC -         The following commands don't require a service name:
AUTOMATIC -         sc <server> <command> <option>
AUTOMATIC -           boot------------(ok | bad) Indicates whether the last boot should
AUTOMATIC -                           be saved as the last-known-good boot configuration
AUTOMATIC -           Lock------------Locks the Service Database
AUTOMATIC -           QueryLock-------Queries the LockStatus for the SCManager Database
AUTOMATIC - EXAMPLE:
AUTOMATIC -         sc start MyService
AUTOMATIC - QUERY and QUERYEX OPTIONS:
AUTOMATIC -         If the query command is followed by a service name
AUTOMATIC -         for that service is returned.  Further options do not apply in
AUTOMATIC -         this case.  If the query command is followed by nothing or one of
AUTOMATIC -         the options listed below
AUTOMATIC -     type=    Type of services to enumerate (driver
AUTOMATIC -              (default = service)
AUTOMATIC -     state=   State of services to enumerate (inactive
AUTOMATIC -              (default = active)
AUTOMATIC -     bufsize= The size (in bytes) of the enumeration buffer
AUTOMATIC -              (default = 4096)
AUTOMATIC -     ri=      The resume index number at which to begin the enumeration
AUTOMATIC -              (default = 0)
AUTOMATIC -     group=   Service group to enumerate
AUTOMATIC -              (default = all groups)
AUTOMATIC - SYNTAX EXAMPLES
AUTOMATIC - sc query                - Enumerates status for active services & drivers
AUTOMATIC - sc query eventlog       - Displays status for the eventlog service
AUTOMATIC - sc queryex eventlog     - Displays extended status for the eventlog service
AUTOMATIC - sc query type= driver   - Enumerates only active drivers
AUTOMATIC - sc query type= service  - Enumerates only Win32 services
AUTOMATIC - sc query state= all     - Enumerates all services & drivers
AUTOMATIC - sc query bufsize= 50    - Enumerates with a 50 byte buffer
AUTOMATIC - sc query ri= 14         - Enumerates with resume index = 14
AUTOMATIC - sc queryex group= ""    - Enumerates active services not in a group
AUTOMATIC - sc query type= interact - Enumerates all interactive services
AUTOMATIC - sc query type= driver group= NDIS     - Enumerates all NDIS drivers

Ответы [ 2 ]

0 голосов
/ 10 июня 2019

Итак, я действительно нашел решение своей проблемы, обнаружив в своей программе различные простые ошибки.Мое решение, если кому-то интересно (вероятно, нет):

@echo off
title Services Script
setlocal enabledelayedexpansion
pause

set "autosvc=;BrokerInfrastructure;BFE;EventSystem;CDPUserSvc_;DiagTrack;CoreMessagingRegistrar;CryptSvc;DusmSvc;DcomLaunch;Dhcp;DPS;TrkWks;Dnscache;gpsvc;LSM;NlaSvc;nsi;Power;Spooler;PcaSvc;RpcSs;RpcEptMapper;SamSs;LanmanServer;ShellHWDetection;SysMain;SENS;SystemEventsBroker;Schedule;Themes;UserManager;ProfSvc;AudioSrv;AudioEndpointBuilder;Wcmsvc;WinDefend;MpsSvc;SecurityHealthService;EventLog;FontCache;Winmgmt;WpnService;WpnUserService_;LanmanWorkstation;MBAMService;^!SASCORE;FileZilla Server;FileZilla;VMware;VMTools;"
set "delayedautosvc=;BITS;CDPSvc;DoSvc;wscsvc;sppsvc;OneSyncSvc_;WSearch;SgrmBroker;MMCSS"
set "demandsvc=;AxInstSV;AJRouter;AppReadiness;AppIDSvc;Appinfo;AppMgmt;AppXSVC;AssignedAccessManagerSvc;BDESVC;wbengine;BTAGService;bthserv;BluetoothUserService_;camsvc;CaptureService_;CertPropSvc;ClipSVC;KeyIso;COMSysApp;Browser;PimIndexMaintenanceSvc_;VaultSvc;DsSvc;DeviceAssociationService;DeviceInstall;DmEnrollmentSvc;DsmSVC;DevicePickerUserSvc_;DevicesFlowUserSvc_;DevQueryBroker;diagsvc;WdiServiceHost;WdiSystemHost;MSDTC;embeddedmode;EFS;EntAppSvc;EapHost;fhsvc;fdPHost;FDResPub;BcastDVRUserService_;GraphicsPerfSvc;hidserv;IKEEXT;UI0Detect;IpxlatCfgSvc;PolicyAgent;KtmRm;lltdsvc;wlpasvc;MessagingService_;diagnosticshub.standardcollector.service;NgcSvc;NgcCtnrSvc;swprv;smphost;InstallService;NcdAutoSetup;NcbService;Netman;NcaSVC;netprofm;NetSetupSvc;ssh-agent;defragsvc;PNRPsvc;p2psvc;p2pimsvc;PerfHost;pla;PlugPlay;PNRPAutoReg;WPDBusEnum;PrintNotify;PrintWorkflowUserSvc_;wercplsupport;QWAVE;RmSvc;seclogon;SstpSvc;SharedRealitySvc;svsvc;SSDPSRV;StateRepository;WiaRpc;StorSvc;TieringEngineService;lmhosts;TapiSrv;TimeBroker;UsoSvc;upnphost;UserDataSvc_;UnistoreSvc_;vds;VSS;WalletService;WarpJITSvc;TokenBroker;WebClient;SDRSVC;wcncsvc;Sense;WdNisSvc;WEPHOSTSVC;WerSvc;Wecsvc;StiSvc;msiserver;LicenseManager;TrustedInstaller;spectrum;PushToInstall;W32Time;wuauserv;WaaSMedicSvc;WinHttpAutoProxySvc;dot3svc;WlanSvc;wmiApSrv;XboxGipSvc;xbgm;BthAvctpSvc;MozillaMaintenance;"

echo CONFIGURING SERVICE SETTINGS...

for /f "skip=1 tokens=1 delims=, " %%i in ('wmic service get name') do ( 
    set tmpry=0
    if "!autosvc:;%%~i;=!" neq "!autosvc!" ( set /a tmpry=2 )
    if "!delayedautosvc:;%%~i;=!" neq "!delayedautosvc!" ( set /a tmpry=4 ) 
    if "!demandsvc:;%%~i;=!" neq "!demandsvc!" ( set /a tmpry=6 )

    if !tmpry! equ 2 ( echo AUTOMATIC - %%~i )
    if !tmpry! equ 4 ( echo DELAYEDAUTOMATIC - %%~i )
    if !tmpry! equ 6 ( echo MANUAL - %%~i )
    if !tmpry! lss 1 ( echo DISABLE - %%~i )
)

echo ARE YOU SURE YOU WANT THESE SETTINGS?
pause

echo Automatic Start: > "C:\Users\%USERNAME%\Desktop\ServiceConfigurations.txt"
for /f "skip=1 tokens=1 delims=, " %%i in ('wmic service get name') do ( 
    set tmpry=0
    if "!autosvc:;%%~i;=!" neq "!autosvc!" ( set /a tmpry=2 )
    if "!delayedautosvc:;%%~i;=!" neq "!delayedautosvc!" ( set /a tmpry=4 ) 
    if "!demandsvc:;%%~i;=!" neq "!demandsvc!" ( set /a tmpry=6 )

    if !tmpry! equ 2 ( 
        sc \\%COMPUTERNAME% config %%~i start= auto )
    if !tmpry! equ 4 ( 
        sc \\%COMPUTERNAME% config %%~i start= delayed-auto )
    if !tmpry! equ 6 ( 
        sc \\%COMPUTERNAME% config %%~i start= demand )
    if !tmpry! lss 1 ( 
        sc \\%COMPUTERNAME% config %%~i start= disabled
        sc \\%COMPUTERNAME% stop %%~i )
)

echo Service settings configured.
pause
exit
0 голосов
/ 05 июня 2019

Ниже приведен пример моего комментария, который просто устанавливает тип запуска, независимо от его текущего режима.Нет необходимости регистрировать текущие значения и сравнивать их в первую очередь, просто внесите необходимые изменения в конфигурацию:

@For %%A In (BrokerInfrastructure,BFE)Do @SC config %%A start= auto
@For %%A In (BITS,CDPSvc)Do @SC config %%A start= delayed-auto
@For %%A In (AxInstSV,AJRouter)Do @SC config %%A start= demand

Вам также необходимо запустить этот скрипт .cmd от имени администратора

[Edit /]

Это расширение вышеприведенного кода, и я прокомментировал использование WMIC для получения не отключенных сервисов.Я включил его, чтобы следовать методологии отключения только тех служб, которые еще не отключены и которых нет в ваших списках конфигурации.

@Echo Off
SetLocal DisableDelayedExpansion

(   For %%A In (BrokerInfrastructure,BFE
    )Do SC config %%A start= auto>CON 2>&1&Echo(\^<%%A\^>
    For %%A In (BITS,CDPSvc
    )Do SC config %%A start= delayed-auto>CON 2>&1&Echo(\^<%%A\^>
    For %%A In (AxInstSV,AJRouter
    )Do SC config %%A start= demand>CON 2>&1&Echo(\^<%%A\^>
)>"mylist.txt"

For /F "Skip=1Delims=" %%A In ('WMIC Service Where "StartMode!='Disabled'"^
 Get Name^|FindStr /IVG:"mylist.txt" 2^>Nul')Do For %%B In (%%A
 )Do SC config %%B start= disabled

Del "mylist.txt"
...